Momento Cache を Node.js で使うためのチートシート
このページでは、Momento Cache を Node.js + TypeScript で素早く使ってみたい方のために必要となる基礎的な API 呼出しを解説しています。ビルド設定ファイルを含めた動作可能な例として、Node.js SDK の例をご確認下さい。
Momento クライアントライブラリをインストール
既存の Node.js プロジェクトにクライアントライブラリをインストールします:
npm install @gomomento/sdk
認証トークンをセットアップする
Momento で認証するためには Momento 認証トークンが必要になります。Momento ウェブコンソールから取得可能です。 トークンを取得したら、環境変数に格納して Momento クライアントから使えるようにします:
export MOMENTO_AUTH_TOKEN=<your Momento token here>
Note: セキュリティ強化のためには、トークンを環境変数ではなく、AWS Secret ManagerやGCP Secret Managerのようなものに格納するのがベストプラクティスですが、ここではデモのために環境変数を利用しています。
ライブラリをインポートして、CacheClient オブジェクトを返却して接続する
このコードで、必要なインポート、そしてそれぞれの他の関数が呼び出す必要のある CacheClient を生成して、メイン関数をセットアップします。
/* eslint-disable @typescript-eslint/no-unused-vars */
import {CacheGet, CreateCache, CacheSet, CacheClient, Configurations, CredentialProvider} from '@gomomento/sdk';
async function main() {
const cacheClient = await CacheClient.create({
configuration: Configurations.Laptop.v1(),
credentialProvider: CredentialProvider.fromEnvironmentVariable({
environmentVariableName: 'MOMENTO_API_KEY',
}),
defaultTtlSeconds: 60,
});
}
main().catch(e => {
console.error(`Uncaught exception while running example: ${JSON.stringify(e)}`);
throw e; // Depending on the environment, this might not be necessary.
});
Momento Cache に新しいキャッシュを作成する
この関数を使ってアカウント内に新しいキャッシュを作成します。
const result = await cacheClient.createCache('test-cache');
if (result instanceof CreateCache.Success) {
console.log("Cache 'test-cache' created");
} else if (result instanceof CreateCache.AlreadyExists) {
console.log("Cache 'test-cache' already exists");
} else if (result instanceof CreateCache.Error) {
throw new Error(
`An error occurred while attempting to create cache 'test-cache': ${result.errorCode()}: ${result.toString()}`
);
}
アカウント内の既存のキャッシュをリストする
アカウント内のキャッシュの名前をシンプルにリストします。
const result = await cacheClient.listCaches();
if (result instanceof ListCaches.Success) {
console.log(
`Caches:\n${result
.getCaches()
.map(c => c.getName())
.join('\n')}\n\n`
);
} else if (result instanceof ListCaches.Error) {
throw new Error(`An error occurred while attempting to list caches: ${result.errorCode()}: ${result.toString()}`);
}
項目をキャッシュに書き込む
書込み操作を行うシンプルな例です。client.set 呼出しでは、TTL はオプショナルです。もし TTL を渡すと、クライアント接続オブジェクトに設定されたデフォルトの TTL 値が上書きされます。
const result = await cacheClient.set('test-cache', 'test-key', 'test-value');
if (result instanceof CacheSet.Success) {
console.log("Key 'test-key' stored successfully");
} else if (result instanceof CacheSet.Error) {
throw new Error(
`An error occurred while attempting to store key 'test-key' in cache 'test-cache': ${result.errorCode()}: ${result.toString()}`
);
}
キャッシュから項目を読み出す
これは、キャッシュから項目を取得するためのシンプルな読み出し操作です。
const result = await cacheClient.get('test-cache', 'test-key');
if (result instanceof CacheGet.Hit) {
console.log(`Retrieved value for key 'test-key': ${result.valueString()}`);
} else if (result instanceof CacheGet.Miss) {
console.log("Key 'test-key' was not found in cache 'test-cache'");
} else if (result instanceof CacheGet.Error) {
throw new Error(
`An error occurred while attempting to get key 'test-key' from cache 'test-cache': ${result.errorCode()}: ${result.toString()}`
);
}
コードを実行する
実行可能な完成された例は JavaScript SDK GitHub レポジトリの examples ディレクトリをご覧下さい。
これらの API 呼出し以上のものは、API リファレンスページで Momento API 呼出しの全種類の詳しい情報をご確認下さい。
同じようなコードで、より高度な呼出しを見るには、このリンクに従って下さい。