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

インターフェース

このドキュメントでは、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.1JwtClaims に追加されました。

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 (部分的なプロパティで初期化)
}
バージョンノート

tenantRolestenantGroupIds はグループベースのロール認可の一環としてバージョン 1.3.1UserContext に追加されました。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')
}
Step Functions連携

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,
};
}
}

認可インターフェース

IGroupRoleResolver

バージョンノート

IGroupRoleResolver はグループベースのロール認可のためにバージョン 1.3.1で追加されました。

グループからロールへのマッピングを解決するためのインターフェース。アプリケーションごとに1つだけ実装し、@GroupRoleResolver() で登録してください。

export interface IGroupRoleResolver {
resolveRoles(input: ResolveGroupRolesInput): Promise<string[]>
}

ResolveGroupRolesInput

export interface ResolveGroupRolesInput {
tenantCode: string // ロールを解決する対象のアクティブテナント
groupIds: string[] // このテナントの `custom:groups` JWT クレームからのグループ ID
claims: JwtClaims // 追加コンテキスト用の完全な JWT クレーム
}

実装例:

import {
GroupRoleResolver,
IGroupRoleResolver,
ResolveGroupRolesInput,
} from '@mbc-cqrs-serverless/core';

// @Injectable() を追加しないこと — @GroupRoleResolver() がシングルトンプロバイダーとして登録します
@GroupRoleResolver()
export class AppGroupRoleResolver implements IGroupRoleResolver {
async resolveRoles({ tenantCode, groupIds }: ResolveGroupRolesInput): Promise<string[]> {
// グループ ID をロールにマッピング — DB、設定などから取得
return groupIds.includes('admin-group') ? ['admin'] : ['user'];
}
}

完全な使用方法のドキュメントは グループベースのロール を参照してください。

通知インターフェース

EmailNotification

メール通知送信用の設定。

export interface EmailNotification {
fromAddr?: string // 送信者アドレス(未指定時はデフォルト使用)
toAddrs: string[] // 必須: 宛先アドレス
ccAddrs?: string[] // CC アドレス
bccAddrs?: string[] // BCC アドレス
subject: string // 必須: メール件名
body: string // 必須: HTML 本文コンテンツ
replyToAddrs?: string[] // 返信先アドレス
attachments?: Attachment[] // ファイル添付
}

export interface Attachment {
filename: string // 添付ファイル名
content: Buffer // Buffer 形式のファイルコンテンツ
contentType?: string // MIME タイプ(例: 'application/pdf')
}

使用例:

await emailService.sendEmail({
toAddrs: ['user@example.com'],
subject: 'Order Confirmation',
body: `<h1>Order Confirmed</h1><p>Your order ${orderCode} has been confirmed.</p>`,
});

モジュール設定インターフェース

CommandModuleOptions

CommandModuleの設定オプション。

export interface CommandModuleOptions {
tableName: string // DynamoDB テーブル名
dataSyncHandlers?: Type<IDataSyncHandler>[] // カスタム同期ハンドラー
skipError?: boolean // 将来の使用のために予約済み(未実装)
disableDefaultHandler?: boolean // デフォルトの DynamoDB データ同期ハンドラーを無効化
}

使用例:

import { Module } from '@nestjs/common';
import { CommandModule } from '@mbc-cqrs-serverless/core';
import { OrderRdsSyncHandler } from './order-rds-sync.handler';

@Module({
imports: [
CommandModule.register({
tableName: 'order',
dataSyncHandlers: [OrderRdsSyncHandler],
disableDefaultHandler: false,
}),
],
})
export class OrderModule {}

SequencesModuleOptions

SequencesModuleの設定オプション。

export interface SequencesModuleOptions {
enableController?: boolean // デフォルトのシーケンスコントローラーの有効・無効
}

イベントインターフェース

SnsEvent

SnsServiceで送信するすべてのSNSメッセージの基底インターフェース。すべてのメッセージはactionフィールドを含める必要があります。ドメイン固有のフィールドを追加するには、このインターフェースを継承してください。

export interface SnsEvent {
action: string // Message action identifier (e.g. 'order-created', 'user-updated') (メッセージアクション識別子、例:'order-created'、'user-updated')
}

使用例と継承パターンについては、Queue — SnsEventを参照してください。

StepFunctionsEvent

AWS Step Functionsからのイベント構造。

export interface StepFunctionsContextExecution {
Id: string // Execution ID (実行ID)
Input: { [id: string]: any } // Input data (入力データ)
Name: string // Execution name (実行名)
RoleArn: string // IAM role ARN (IAMロールARN)
StartTime: string // Execution start time (実行開始時刻)
}

export interface StepFunctionsContextState {
EnteredTime: string // State entered time (ステート開始時刻)
Name: string // State name (ステート名)
RetryCount: number // Retry count (リトライ回数)
}

export interface StepFunctionsContextStateMachine {
Id: string // State machine ID (ステートマシンID)
Name: string // State machine name (ステートマシン名)
}

export interface StepFunctionsContext {
Execution: StepFunctionsContextExecution
State: StepFunctionsContextState
StateMachine: StepFunctionsContextStateMachine
}

export interface StepFunctionsEvent<TInput> {
input: TInput // Input data passed to the state (ステートに渡された入力データ)
context: StepFunctionsContext // Step Functions context information (Step Functionsコンテキスト情報)
}

型ユーティリティ

共通型ヘルパー

// Partial type that requires specific keys (特定のキーを必須とする部分型)
type RequiredPick<T, K extends keyof T> = Partial<T> & Pick<T, K>;

// Deep partial type (ディープパーシャル型)
type DeepPartial<T> = {
[P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];
};

// Entity without audit fields (監査フィールドなしのエンティティ)
type EntityInput<T> = Omit<T, 'createdAt' | 'createdBy' | 'updatedAt' | 'updatedBy'>;

関連ドキュメント