メインコンテンツまでスキップ

JavaScriptでMomento Cacheを始めるJavaScriptでMomento Cacheを始める

Momentoは2つのJavaScript SDKを提供しています。1つはNode.js用1つはブラウザその他のWebアプリケーション用です。2つのSDKは同じAPIを持っているため、import文以外は同じコードに見えますが、異なるJavaScript実行環境において最適なパフォーマンスと互換性を保つように作られています。

このページには、Momento Cache をすぐに使い始めるために必要な基本的な情報が記載されています。より詳細な情報や例については、上記のリンク先の SDK ページを参照してください。

Momento SDKをインストールする

既存のNode.jsプロジェクトにMomento Node.js SDKをインストールするには:

npm install @gomomento/sdk

または、既存のブラウザ アプリケーション プロジェクトに Momento Web SDK をインストールします:

npm install @gomomento/sdk-web
ヒント

gomento/sdkまたは@gomento/sdk-webのどちらか片方だけが必要である。両方は必要ない。

APIキーの設定

Momentoで認証するには、Momento APIキーが必要です。 Momento Web Consoleから取得できます。 APIキーを取得したら、Momentoクライアントが利用できるように環境変数に保存してください:

export MOMENTO_API_KEY=<your Momento API key here>

Note: セキュリティ強化のためには、APIキーを環境変数ではなく、AWS Secret ManagerやGCP Secret Managerのようなものに入れるのがベストプラクティスだが、ここではデモのためにAPIキーを使っています。

ライブラリをインポートし、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(cacheName);
if (result instanceof CreateCache.Success) {
console.log(`Cache '${cacheName}' created`);
} else if (result instanceof CreateCache.AlreadyExists) {
console.log(`Cache '${cacheName}' already exists`);
} else if (result instanceof CreateCache.Error) {
throw new Error(
`An error occurred while attempting to create cache '${cacheName}': ${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(cacheName, '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 '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}

キャッシュからアイテムを読み込む

これは、キャッシュから項目を取得する単純な読み取り操作の例である。

const result = await cacheClient.get(cacheName, '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 '${cacheName}'`);
} else if (result instanceof CacheGet.Error) {
throw new Error(
`An error occurred while attempting to get key 'test-key' from cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}

コードの実行

JavaScript SDK GitHub repo examples directoryに完全な動作例があります。

備考

これらの基本的なAPIコール以外にも、MomentoのAPIコールの詳細については、APIリファレンスページをチェックしてください。

より高度なコール用の同じタイプのコードを見るには、このリンクをたどってください。