JavaScriptでMomento Topicsを始める
Momentoは2つのJavaScript SDKを提供しています。1つはNode.js用、1つはブラウザその他のWebアプリケーション用です。2つのSDKは同じAPIを持っているため、import
文以外は同じコードに見えますが、異なるJavaScript実行環境において最適なパフォーマンスと互換性を保つように作られています。
このページには、Momento Topicsをすぐに使い始めるために必要な基本的な情報が記載されています。より詳細な情報やサンプルについては、上記の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 keyが必要です。できれば、Momento Web Console から取得できます。 トークンを取得したら、それを環境変数に保存し、Momentoクライアントがそれを使用できるようにします:
export MOMENTO_AUTH_TOKEN=<your Momento token here>
Note: セキュリティ強化のためには、トークンを環境変数ではなく、AWS Secret ManagerやGCP Secret Managerのようなものに格納するのがベストプラクティスだが、ここではデモのために使用していまます。
ライブラリのインポートとTopicClientオブジェクトの作成
このコードでは、メイン関数を設定し、必要なインポートを取り込み、パブ/サブ・トピックとの対話に使用する TopicClient をインスタンス化します。
/* eslint-disable @typescript-eslint/no-unused-vars */
import {TopicClient, TopicConfigurations, CredentialProvider} from '@gomomento/sdk';
function main() {
const cacheClient = new TopicClient({
configuration: TopicConfigurations.Default.latest(),
credentialProvider: CredentialProvider.fromEnvironmentVariable({
environmentVariableName: 'MOMENTO_API_KEY',
}),
});
}
try {
main();
} catch (e) {
console.error(`Uncaught exception while running example: ${JSON.stringify(e)}`);
throw e;
}
トピックへのメッセージの登録と公開
この例では、"test-cache" という名前の Momento Cache の "test-topic" というトピックを購読し、購読が成功したらそのトピックに公開します。
const result = await topicClient.subscribe(cacheName, 'test-topic', {
onError: () => {
return;
},
onItem: (item: TopicItem) => {
console.log(`Received an item on subscription for 'test-topic': ${item.value().toString()}`);
return;
},
});
if (result instanceof TopicSubscribe.Subscription) {
console.log("Successfully subscribed to topic 'test-topic'");
console.log("Publishing a value to the topic 'test-topic'");
// Publish a value
await topicClient.publish(cacheName, 'test-topic', 'test-value');
console.log('Waiting for the published value to be received.');
await new Promise(resolve => setTimeout(resolve, 1000));
// Need to close the stream before the example ends or else the example will hang.
result.unsubscribe();
} else if (result instanceof TopicSubscribe.Error) {
throw new Error(
`An error occurred while attempting to subscribe to the topic 'test-topic' in cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}
コードの実行
JavaScript SDK GitHub repo examples directory](https://github.com/momentohq/client-sdk-javascript/blob/main/examples)に完全な動作例があります。
これらの基本的なAPIコール以外にも、MomentoのAPIコールの詳細については、APIリファレンスページを参照してください。
より高度なコール用の同じタイプのコードを見るには、このリンクをたどってください。