イベントの再生サンプル: コードのウォークスルー
イベントの再生の JavaScript サンプル
このデュラブルストリーミングのサンプルには、cometdReplayExtension 再生拡張を使用してイベントを再生する JavaScript コードが含まれています。このコードは DurableGenericEventDisplay コンポーネントと DurablePushTopicEventDisplay Visualforce コンポーネント内にあり、Visualforce ページに埋め込まれています。JavaScript を Visualforce ページに直接追加するか、Visualforce コンポーネントを再利用できます。このセクションではサンプルコンポーネント部分が強調表示されています。
まず、Salesforce が提供する CometD 拡張 cometdReplayExtension を登録してイベントを再生します。このスニペットでは、ストリーミングチャネルと再生オプションも設定します。registerExtension の最初の引数は、拡張の登録解除に使用する任意の名前です。
1// Register Generic Streaming Replay extension
2var replayExtension = new cometdReplayExtension();
3replayExtension.setChannel(<Streaming Channel to Subscribe to>);
4replayExtension.setReplay(<Event Replay Option>);
5cometd.registerExtension('myReplayExtensionName', replayExtension);次に、クライアントが CometD 再生エンドポイントに接続します。エンドポイントの API バージョンは 37.0 以降である必要があります。現在のセッションのセッション ID 値が Authorization ヘッダーで渡されます。
1// Connect to the CometD endpoint
2cometd.init({
3 url: 'https://Salesforce_instance/cometd/37.0/',
4 requestHeaders: { Authorization: 'OAuth <Session ID>'}
5});最後に、CometD subscribe() 関数のコールバックを指定します。チャネルでメッセージが受信されたときに、CometD がこのコールバック関数をコールします。このサンプルでは、コールバック関数によってページにメッセージデータが表示されます。ID 値が "content" の div HTML 要素にデータが追加されます。
1// Subscribe to a topic. JSON-encoded update will be returned in the callback
2cometd.subscribe(channel, function(message) {
3 $('#content').append('<p>Notification ' +
4
'on channel: ' + JSON.stringify(message.channel) + '<br>' +
5
'Payload: ' + JSON.stringify(message.data.payload) + '<br>' +
6
'Replay Id: ' + JSON.stringify(message.data.event.replayId) + '<br>' +
7
'Full message: ' + JSON.stringify(message) + '</p>');
8
}
9);cometdReplayExtension 拡張
cometdReplayExtension では、受信メッセージと送信メッセージでコールされるコールバックを使用できます。これらのコールバックは、ハンドシェイク時に拡張の登録を確認し、登録時に再生オプションを設定するロジックを実装します。
ハンドシェイク時に、受信メッセージのコールバックで再生拡張が登録されているかどうかが確認されます。登録されている場合は、_extensionEnabled 変数が true に設定されます。
1this.incoming = function(message) {
2 if (message.channel === '/meta/handshake') {
3 if (message.ext && message.ext[REPLAY_FROM_KEY] == true) {
4 _extensionEnabled = true;
5 }
6 }
7}登録時に、送信メッセージのコールバックで _extensionEnabled 変数を使用して再生拡張が登録されているかどうかが確認されます。拡張が登録されている場合、コールバックは指定された再生オプションに基づいてイベントに登録します。このサンプルでは、拡張の setReplay() 関数をコールして再生オプションを設定しています。
1this.outgoing = function(message) {
2 if (message.channel === '/meta/subscribe') {
3 if (_extensionEnabled) {
4 if (!message.ext) {
5 message.ext = {};
6 }
7 var replayFromMap = {};
8 replayFromMap[_channel] = _replay;
9 // add "ext : { "replay" : { CHANNEL : REPLAY_VALUE }}"
10 // to subscribe message.
11 message.ext[REPLAY_FROM_KEY] = replayFromMap;
12 }
13 }
14};