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

Node.js と Momento Topics のチートシート

Node.js + TypeScript で Momento Topics をすぐに使い始める必要がある場合、このページには基本的に必要となるAPI呼び出しを記載しています。Node.js SDK の例には、ビルド設定ファイルを含む、実用的な例が記載されています。

Momento クライアント・ライブラリをインストールする

既存の Node.js プロジェクトにクライアント・ライブラリをインストールします:

npm install @gomomento/sdk

認証トークンを設定する

Momento で認証するには、Momento API key が必要です。できれば、Momento Web コンソール から取得できます。 トークンを取得したら、Momento クライアントがそれを利用できるように環境変数に保存します:

export MOMENTO_API_KEY=<your key 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('test-cache', 'test-topic', {
onError: () => {
return;
},
onItem: (item: TopicItem) => {
console.log(`Publishing values to the topic 'test-topic': ${item.value().toString()}`);
return;
},
});
if (result instanceof TopicSubscribe.Subscription) {
console.log("Successfully subscribed to topic 'test-topic'");

// Publish a value
await topicClient.publish('test-cache', 'test-topic', 'test-value');

// Wait for published values to be received.
setTimeout(() => {
console.log('Waiting for the published values');
}, 2000);

// 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 'test-cache': ${result.errorCode()}: ${result.toString()}`
);
}

コードの実行

GitHubリポジトリのJavaScript SDKにあるexamplesに動作例があります。

備考

これらの基本的なAPI呼び出し以外の詳細については、APIリファレンスページを参照してください。

このリンクから、同じタイプの、より高度なAPI呼び出しのコード例を見ることができます。