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

サンプル

このセクションでは、一般的なユースケースの実践例と実装ガイドを提供します。各サンプルは、本番環境対応の完全なコードで実際のシナリオを示しています。

利用可能なサンプル

サンプル説明主要な概念
ディレクトリ組織階層とユーザー管理ネスト構造、リレーション、検索
アンケートテンプレートバリデーション付き動的フォームビルダースキーマ設計、バージョニング、複雑な属性

実装パターン

各サンプルは一貫したパターンに従っています:

1. エンティティ設計

// Define your entity with proper key structure
export class OrderEntity extends BaseEntity {
pk: string; // TENANT#tenantCode
sk: string; // ORDER#orderId
id: string;
tenantCode: string;
code: string;
name: string;
attributes: OrderAttributes;
}

2. コマンドパターン

// Create commands for state changes
async createOrder(dto: CreateOrderDto, context: IInvoke) {
const orderId = await this.sequencesService.generateSequenceItem({
tenantCode: dto.tenantCode,
typeCode: 'ORDER',
});

return this.commandService.publishAsync(
{
pk: `${dto.tenantCode}#ORDER`,
sk: `ORDER#${orderId.formattedNo}`,
code: orderId.formattedNo,
name: dto.name,
tenantCode: dto.tenantCode,
attributes: dto.attributes,
},
{ invokeContext: context },
);
}

3. クエリパターン

// Query data with proper filtering
async listOrders(tenantCode: string, options: ListOptions) {
return this.dataService.listItemsByPk(
`${tenantCode}#ORDER`,
{
limit: options.limit,
startFromSk: options.lastSk,
},
);
}

4. イベントハンドラー

// Handle data sync events
@EventHandler(OrderDataSyncEvent)
export class OrderDataSyncHandler implements IEventHandler<OrderDataSyncEvent> {
async execute(event: OrderDataSyncEvent): Promise<void> {
// Sync to read model (RDS, OpenSearch, etc.)
await this.syncToReadModel(event.data);
}
}

ベストプラクティス

キー設計

  • 一貫したプレフィックスパターンを使用: TENANT#codeORDER#id
  • パーティションキーは均等に分散されるよう十分に広く保つ
  • 階層データにはソートキーを使用

エラーハンドリング

import { ConditionalCheckFailedException } from '@aws-sdk/client-dynamodb';
import { ConflictException } from '@nestjs/common';

try {
await this.commandService.publishAsync(command, options);
} catch (error) {
if (error instanceof ConditionalCheckFailedException) {
// Handle optimistic locking conflict (version mismatch)
throw new ConflictException('Item was modified by another process');
}
throw error;
}

テスト

describe('OrderService', () => {
it('should create order with sequence', async () => {
const result = await service.createOrder(mockDto, mockContext);
expect(result.code).toMatch(/^ORD-\d{6}$/);
});
});

サンプルを探索