通知モジュール
NotificationModuleは、MBC CQRS Serverlessフレームワークで2種類の通知機能を提供します:
- WebSocketベースの更新用のリアルタイム通知(AWS AppSync経由)
- メール送信用のメール通知(AWS SES経由)
アーキテクチャ
リアルタイム通知
概要
DynamoDBでデータ変更が発生すると、リアルタイム通知が自動的に送信されます。システムはAWS AppSyncを使用して、購読中のWebSocketクライアントに通知を配信します。
INotificationインターフェース
通知ペイロードの構造:
interface INotification {
id: string; // Unique notification ID (一意の通知ID)
table: string; // Source DynamoDB table name (ソースDynamoDBテーブル名)
pk: string; // 変更されたアイテムのパーティションキー
sk: string; // 変更されたアイテムのソートキー
tenantCode: string; // Tenant code for filtering notifications (通知フィルタリング用のテナントコード)
action: string; // Type of change: 'INSERT', 'MODIFY', 'REMOVE' (変更タイプ)
content?: object; // Optional payload with changed data (変更データを含むオプションのペイロード)
}
AppSyncService
AppSyncServiceはリアルタイム通知をAppSyncに送信し、WebSocket経由で配信します。
メソッド: sendMessage(msg: INotification): Promise<void>
GraphQLミューテーション経由でAppSyncに通知を送信します。通知はすべての購読中のWebSocketクライアントに配信されます。
sendMessage の戻り値型はバージョン1.3.0で Promise<any> から Promise<void> に変更されました。テストでこのメソッドを mockResolvedValue(null) でモックしている場合は mockResolvedValue(undefined) に更新して ください。詳細はv1.3.0移行ガイドを参照してください。
await this.appSyncService.sendMessage({
id: "unique-id",
table: "my-table",
pk: "ITEM#tenant1",
sk: "ITEM#001",
tenantCode: "tenant1",
action: "MODIFY",
content: { status: "updated" },
});
設定
以下の環境変数を設定してください:
APPSYNC_ENDPOINT=https://xxxxx.appsync-api.ap-northeast-1.amazonaws.com/graphql
APPSYNC_API_KEY=da2-xxxxxxxxxx # Optional: Use API key auth instead of IAM (オプション: IAMの代わりにAPIキー認証を使用)
使用方法
import { Injectable } from "@nestjs/common";
import { AppSyncService, INotification } from "@mbc-cqrs-serverless/core";
@Injectable()
export class MyService {
constructor(private readonly appSyncService: AppSyncService) {}
async notifyClients() {
const notification: INotification = {
id: "notification-123",
table: "my-table",
pk: "ITEM#tenant1",
sk: "ITEM#item001",
tenantCode: "tenant1",
action: "MODIFY",
content: { status: "updated" },
};
await this.appSyncService.sendMessage(notification);
}
}
認証
AppSyncServiceは2つの認証方法をサポートしています:
- API キー:
APPSYNC_API_KEY環境変数を設定 - IAM署名V4: APIキーが設定されていない場合に自動的に使用
自動通知
フレームワークはデータ変更時に以下の流れで自動的に通知を送信します:
- DynamoDBストリームが
NotificationEventHandlerをトリガー - ハンドラーが変更情報を抽出し
INotificationを作成 AppSyncService.sendMessage()がAppSyncに配信- 接続されたクライアントがWebSocket購読経由で更新を受信
NotificationEvent
NotificationEventクラスはSQSからの通知イベントを表します。IEventを実装し、通知データを含むSQSレコードをラップします。
import { NotificationEvent } from "@mbc-cqrs-serverless/core";
class NotificationEvent implements IEvent, SQSRecord {
source: string;
messageId: string;
receiptHandle: string;
body: string; // JSON string containing INotification data (INotificationデータを含むJSON文字列)
attributes: SQSRecordAttributes;
messageAttributes: SQSMessageAttributes;
md5OfBody: string;
eventSource: string;
eventSourceARN: string;
awsRegion: string;
// Creates a NotificationEvent from an SQS record (SQSレコードからNotificationEventを作成)
fromSqsRecord(record: SQSRecord): NotificationEvent;
}
NotificationEventHandler
NotificationEventHandlerはNotificationEventを処理してAppSyncに通知を送信する組み込みイベントハンドラーです。通知モジュールを使用する際に自動的に登録されます。
import { EventHandler, IEventHandler, NotificationEvent } from "@mbc-cqrs-serverless/core";
@EventHandler(NotificationEvent)
export class NotificationEventHandler implements IEventHandler<NotificationEvent> {
async execute(event: NotificationEvent): Promise<void> {
// Parses the notification from event body (イベント本文から通知をパース)
// Sends to AppSync via sendMessage() (sendMessage()経由でAppSyncに送信)
}
}
通常、このハンドラーと直接やり取りする必要はありません - SQSキューに通知が発行されると自動的に動作します。
AppSync Events API(オプトイン)
AppSyncEventsService とデュアルパブリッシ ュサポートは バージョン 1.3.0 で追加されました。
概要
AppSyncEventsService は AWS AppSync Events API(スキーマ不要の HTTP pub/sub サービス)をベースにした、代替(または補完)のリアルタイムトランスポートを提供します。GraphQL サブスクリプションとは異なり、GraphQL スキーマが不要で、クライアントはワイルドカードチャンネルパスでサブスクライブします。
NOTIFICATION_TRANSPORTS=appsync-event を設定してオプトインします。NOTIFICATION_TRANSPORTS=appsync-graphql,appsync-event と両方のエンドポイントを設定すると、フレームワークは両方のトランスポートにデュアルパブリッシュし、ダウンタイムなしのマイグレーションを可能にします。
メソッド: sendMessage(msg: INotification): Promise<void>
AppSync Events チャンネルに通知をパブリッシュします。通知はサブスクライブ中のすべてのクライアントに配信されます。
await this.appSyncEventsService.sendMessage({
id: "command-123",
table: "orders-table",
pk: "ORDER#tenant1",
sk: "ORDER#001",
tenantCode: "tenant1",
action: "MODIFY",
content: { status: "confirmed" },
});