DataService
概要
DataServiceはCQRSパターンのクエリ側であり、DynamoDBに保存されたデータに対する効率的な読み取り操作を提供します。クエリに最適化されたデータテーブル(読み取りモデル)からのすべての読み取り操作を処理します。
DataServiceを使用する前に、CommandServiceセクションで説明されているようにCommandModuleをセットアップする必要があります。
メソッド
async getItem(key: DetailKey): Promise<DataModel>
getItemメソッドは、指定された詳細キー/主キーを持つアイテムの属性セットを返します。一致するアイテムがない場合、getItemはundefinedを返します。
例:
import { DataService, DataModel } from '@mbc-cqrs-serverless/core';
import { Injectable, NotFoundException } from '@nestjs/common';
@Injectable()
export class CatService {
constructor(private readonly dataService: DataService) {}
async getCat(pk: string, sk: string): Promise<CatDataEntity> {
const item = await this.dataService.getItem({ pk, sk });
if (!item) {
throw new NotFoundException('Cat not found');
}
return new CatDataEntity(item as CatDataEntity);
}
}
async listItemsByPk(pk: string, opts?: ListItemsOptions): Promise<DataListEntity>
listItemsByPkメソッドは、パーティションキーに一致する1つ以上のアイテムを返します。フィルタリング、ページネーション、ソートをサポートしています。
基本的な使い方
主キー(pk)でアイテムを一覧取得:
const res = await this.dataService.listItemsByPk(pk);
return new CatListEntity(res);
ソートキーフィルター付き
主キー(pk)でアイテムを一覧取得し、ソートキー(sk)にフィルター式を使用します。例えば、ソートキーがCAT#で始まるアイテムを取得し、100件に制限:
import { KEY_SEPARATOR } from '@mbc-cqrs-serverless/core';
const query = {
sk: {
skExpression: 'begins_with(sk, :typeCode)',
skAttributeValues: {
':typeCode': `CAT${KEY_SEPARATOR}`,
},
},
limit: 100,
};
const res = await this.dataService.listItemsByPk(pk, query);
return new CatDataListEntity(res);