インターフェース
このドキュメントでは、MBC CQRS Serverlessフレームワークで使用されるすべてのTypeScriptインターフェースの包括的なリファレンスを提供します。
コアインターフェース
コマンドインターフェース
CommandInputModel
新しいコマンドを作成するためのプライマリインターフェース。新しいエンティティを発行する際に使用します。
export interface CommandInputModel {
pk: string // パーティションキー(例: "ORDER#tenant001")
sk: string // ソートキー(例: "ORDER#ORD001")— バージョンサフィックス不要
id: string // 一意識別子(例: UUID)
code: string // ビジネスコード(例: "ORD001")
name: string // 表示名
version: number // 楽観的ロック用バージョン番号
tenantCode: string // テナント識別子
type: string // エンティティタイプ(例: "ORDER")
isDeleted?: boolean // 論理削除フラグ
seq?: number // シーケンス番号(自動生成)
ttl?: number // 有効期限(秒)
attributes?: Record<string, any> // カスタムドメイン属性
}
使用例:
const orderInput: CommandInputModel = {
pk: 'ORDER#tenant001',
sk: 'ORDER#ORD001', // @version サフィックス不要 — version は別フィールド
id: crypto.randomUUID(),
code: 'ORD001',
name: 'Customer Order',
version: 0, // 新規エンティティには VERSION_FIRST を使用
tenantCode: 'tenant001',
type: 'ORDER',
attributes: {
customerId: 'CUST001',
totalAmount: 1500,
status: 'pending',
},
};
CommandPartialInputModel
部分更新に使用します。pk、sk、versionのみが必須です。
export interface CommandPartialInputModel extends Partial<CommandInputModel> {
pk: string // 必須: パーティションキー
sk: string // 必須: ソートキー
version: number // 必須: 楽観的ロック用の現在バージョン
}
使用例:
const partialUpdate: CommandPartialInputModel = {
pk: 'ORDER#tenant001',
sk: 'ORDER#ORD001',
version: 2, // 現在のバージョンと一致する必要があります
name: 'Updated Order Name',
attributes: {
status: 'confirmed',
},
};
ICommandOptions
コマンド発行メソッドに渡されるオプション。
export interface ICommandOptions {
source?: string // 追跡用ソース識別子
requestId?: string // トレーシング用リクエスト ID
invokeContext: IInvoke // 必須: 呼び出しコンテキスト
}
使用例:
const options: ICommandOptions = {
source: 'order-service',
requestId: invokeContext.context.awsRequestId,
invokeContext, // Injected via @INVOKE_CONTEXT() decorator (@INVOKE_CONTEXT()デコレーターで注入)
};
キーインターフェース
DetailKey
DynamoDBアイテムのプライマリキーを表します。
export interface DetailKey {
pk: string // パーティションキー
sk: string // ソートキー
}
コンテキストインターフェース
IInvoke
Lambda/Expressのイベントとコンテキストを含む呼 び出しコンテキスト。
export interface IInvoke {
event?: IInvokeEvent // Request event (headers, requestContext, etc.) (リクエストイベント(headers, requestContext等))
context?: IInvokeContext // Lambda context (requestId, functionName, etc.) (Lambdaコンテキスト(requestId, functionName等))
}
IInvokeEvent
API GatewayまたはExpressからのHTTPリクエストイベント構造。
export interface IInvokeEvent {
version?: string
routeKey?: string // e.g., "POST /api/resource" (例: "POST /api/resource")
rawPath?: string
rawQueryString?: string
headers?: Record<string, string>
requestContext?: {
accountId?: string
apiId?: string
domainName?: string
domainPrefix?: string
http?: {
method?: string
path?: string
protocol?: string
sourceIp?: string // Client IP address (クライアントIPアドレス)
userAgent?: string
}
requestId?: string
stage?: string
time?: string
timeEpoch?: number
authorizer?: {
jwt?: {
claims?: JwtClaims // Decoded JWT claims (デコードされたJWTクレーム)
scopes?: string[]
}
}
}
isBase64Encoded?: boolean
}
IInvokeContext
Lambda実行コンテキスト情報。
export interface IInvokeContext {
functionName?: string // Lambda function name (Lambda関数名)
functionVersion?: string // Lambda function version (Lambda関数バージョン)
invokedFunctionArn?: string // Lambda ARN (LambdaのARN)
memoryLimitInMB?: string // Memory limit (メモリ制限)
awsRequestId?: string // AWS request ID for tracing (トレース用AWSリクエストID)
logGroupName?: string // CloudWatch log group (CloudWatchロググループ)
logStreamName?: string // CloudWatch log stream (CloudWatchログストリーム)
identity?: {
cognitoIdentityId?: string
cognitoIdentityPoolId?: string
}
}
JwtClaims
CognitoからのJWTトークンクレーム構造。
export interface JwtClaims {
sub: string // Cognito user ID (UUID) (CognitoユーザーID)
iss: string // Token issuer URL (トークン発行者URL)
username?: string
'cognito:groups'?: string[] // Cognito groups the user belongs to (ユーザーが所属するCognitoグループ)
'cognito:username': string // Cognito username (Cognitoユーザー名)
origin_jti?: string // Original JWT ID (元のJWT ID)
client_id?: string // OAuth client ID (OAuthクライアントID)
scope?: string // OAuth scopes (OAuthスコープ)
aud: string // Audience (client ID) (オーディエンス/クライアントID)
event_id: string
token_use: string // Token type (id or access) (トークンタイプ: id または access)
auth_time: number // Authentication timestamp (認証タイムスタンプ)
name: string // User's display name (ユーザー表示名)
'custom:tenant'?: string // Custom claim for tenant code (テナントコード用カスタムクレーム)
'custom:roles'?: string // Custom claim for roles JSON array (ロールJSON配列用カスタムクレーム)
'custom:groups'?: string // Custom claim for tenant group memberships JSON array (テナントグループ所属のJSON配列カスタムクレーム)
exp: number // Token expiration timestamp (トークン有効期限タイムスタンプ)
email: string
email_verified?: boolean
iat: number // Token issued at timestamp (トークン発行タイムスタンプ)
jti: string // JWT ID (JWT識別子)
}
カスタムクレームの例:
// The custom:roles claim contains a JSON array of role assignments (custom:rolesクレームはロール 割り当てのJSON配列を含む)
// [{"tenant":"","role":"user"},{"tenant":"9999","role":"admin"}]
// - Empty tenant ("") means the role applies globally (空のテナント("")はロールがグローバルに適用されることを意味する)
// - Specific tenant means the role applies only to that tenant (特定のテナントはロールがそのテナントのみに適用されることを意味する)
custom:groups クレームはグループベースのロール認可の一環としてバージョン 1.3.1で JwtClaims に追加されました。
UserContext
認証トークンから抽出されるユーザーコンテキストクラス。
export class UserContext {
userId: string // Cognito ユーザー ID(JWT の sub クレームから)
tenantRole: string // テナント内のユーザーロール
tenantCode: string // 現在のテナントコード
tenantRoles: string[] // Direct roles for the active tenant (excludes group-derived roles) (アクティブテナントの直接ロール、グループ由来ロールを除く)
tenantGroupIds: string[] // Group IDs from custom:groups for the active tenant (custom:groups由来のグループID)
constructor(partial: Partial<UserContext>) // Initialize with partial properties (部分的なプロパティで初期化)
}
tenantRoles と tenantGroupIds はグループベースのロール認可の一環としてバージョン 1.3.1で UserContext に追加されました。tenantRole(単数形)は後方互換性のために残されています。
使用例:
import { getUserContext, IInvoke } from '@mbc-cqrs-serverless/core';
// Extract user context from IInvoke or ExecutionContext (IInvokeまたはExecutionContextからユーザーコンテキストを抽出)
const userContext = getUserContext(invokeContext);
console.log(userContext.userId); // '92ca4f68-9ac6-4080-9ae2-2f02a86206a4'
console.log(userContext.tenantCode); // 'tenant001'
console.log(userContext.tenantRole); // 'admin'
データインターフェース
エンティティインターフェース
CommandModel
コマンドエンティティ(書き込みモデル)のインターフェース。
export interface CommandModel extends CommandInputModel {
status?: string // Processing status (e.g., 'PENDING', 'COMPLETED', 'FAILED') (処理ステータス: 'PENDING', 'COMPLETED', 'FAILED'等)
source?: string // Event source identifier (e.g., 'POST /api/master', 'SQS') (イベントソース識別子('POST /api/master', 'SQS'等))
requestId?: string // Unique request ID for tracing and idempotency (トレースと冪等性のための一意のリクエストID)
createdAt?: Date // Timestamp when the command was created (コマンド作成時のタイムスタンプ)
updatedAt?: Date // Timestamp when the command was last updated (コマンド最終更新時のタイムスタンプ)
createdBy?: string // User ID who created the command (コマンドを作成したユーザーID)
updatedBy?: string // User ID who last updated the command (コマンドを最後に更新したユーザーID)
createdIp?: string // IP address of the creator (作成者のIPアドレス)
updatedIp?: string // IP address of the last updater (最終更新者のIPアドレス)
taskToken?: string // Step Functions task token for async workflows (非同期ワークフロー用のStep Functionsタスクトークン)
syncMode?: CommandSyncMode // 'SYNC' when the command was applied via synchronous publish (同期publishで適用されたコマンドは'SYNC')
}
taskTokenフィールドは、AWS Step Functionsコールバックパターンと統合する際に使用されます。Step Functionsステートマシンがタスクトークンでアプリケーションを呼び出す場合、CommandService.updateTaskToken()を使用してトークンを保存します。その後、AWS SDKのSendTaskSuccessCommandまたはSendTaskFailureCommandでトークンを使用してタスク完了を通知します。
DataModel
データエンティティ(読み取りモデル)の基本インターフェース。
export interface DataModel extends Omit<CommandModel, 'status'> {
cpk?: string // Command partition key - references source command record (コマンドパーティションキー - ソースコマンドレコードへの参照)
csk?: string // Command sort key with version - references exact command version (バージョン付きコマンドソートキー - 正確なコマンドバージョンへの参照)
}
エンティティクラス
CommandEntity
APIレスポンス用にCommandModelを実装したクラス。Swaggerデコレータを含みます。
export class CommandEntity implements CommandModel {
// All properties from CommandModel (CommandModelのすべてのプロパティ)
pk: string
sk: string
// ...
get key(): DetailKey // Returns { pk, sk } for DynamoDB operations (DynamoDB操作用の { pk, sk } を返す)
}
使用例:
const command: CommandEntity = await commandService.getItem({
pk: 'ORDER#tenant001',
sk: 'ORDER#ORD001',
});
// Access the DynamoDB key pair (DynamoDBキーペアにアクセス)
const key = command.key; // { pk: 'ORDER#tenant001', sk: 'ORDER#ORD001' }
DataEntity
APIレスポンス用にDataModelを実装したクラス。Swaggerデコレータを含みます。
export class DataEntity implements DataModel {
// All properties from DataModel (DataModelのすべてのプロパティ)
pk: string
sk: string
// ...
constructor(data: Partial<DataEntity>) // Initialize with partial properties (部分的なプロパティで初期化)
get key(): DetailKey // Returns { pk, sk } for DynamoDB operations (DynamoDB操作用の { pk, sk } を返す)
}
使用例:
const data: DataEntity = await dataService.getItem({
pk: 'ORDER#tenant001',
sk: 'ORDER#ORD001',
});
// Access the DynamoDB key pair (DynamoDBキーペアにアクセス)
const key = data.key; // { pk: 'ORDER#tenant001', sk: 'ORDER#ORD001' }
リストレスポンスインターフェース
DataListEntity
データクエリ用のページネーション付きリストレスポンス。
export class DataListEntity {
items: DataEntity[] // エンティティの配列
total?: number // 総件数(利用可能な場合)
lastSk?: string // ページネーションカーソル(最後のソートキー)
constructor(data: Partial<DataListEntity>) // Initialize with partial properties (部分的なプロパティで初期化)
}
使用例:
const result = await dataService.listItemsByPk('ORDER#tenant001', {
limit: 20,
startFromSk: previousLastSk,
});
// ページネーション
if (result.lastSk) {
// More items available - use result.lastSk for next page (追加アイテムあり - 次ページにresult.lastSkを使用)
}
サービスインターフェース
同期ハンドラーインターフェース
IDataSyncHandler
データ同期ハンドラーを実装するためのインターフェース。前進(up)およびロールバック(down)操作の両方を処理します。
export interface IDataSyncHandler<TExecuteResult = any, TRollbackResult = any> {
readonly type?: string // オプションの型識別子
/**
* Sync data when a command is executed.
* Called automatically by the framework during command processing.
*/
up(cmd: CommandModel): Promise<TExecuteResult>
/**
* Reserved for rollback operations.
* Note: This method is NOT automatically called by the framework.
* Implement this for manual rollback scenarios in your application.
*/
down(cmd: CommandModel): Promise<TRollbackResult>
}
実装例:
import { Injectable } from '@nestjs/common';
import { CommandModel, IDataSyncHandler } from '@mbc-cqrs-serverless/core';
import { PrismaService } from 'src/prisma';
@Injectable()
export class OrderRdsSyncHandler implements IDataSyncHandler {
readonly type = 'ORDER';
constructor(private readonly prisma: PrismaService) {}
async up(cmd: CommandModel): Promise<void> {
if (cmd.isDeleted) {
await this.prisma.order.delete({
where: { id: cmd.id },
});
} else {
await this.prisma.order.upsert({
where: { id: cmd.id },
create: this.toRdsModel(cmd),
update: this.toRdsModel(cmd),
});
}
}
async down(cmd: CommandModel): Promise<void> {
// Rollback logic - restore previous state (ロールバックロジック - 前の状態を復元)
await this.prisma.order.delete({
where: { id: cmd.id },
});
}
private toRdsModel(cmd: CommandModel) {
return {
id: cmd.id,
code: cmd.code,
name: cmd.name,
...cmd.attributes,
};
}
}