Skip to content

AIダンジョンゲーム

モジュール2: ゲームAPIの実装

まずゲームAPIの実装から始めます。合計4つのAPIを作成する必要があります:

  1. createGame - 新しいゲームインスタンスを作成
  2. queryGames - 保存済みゲームのページネーション付きリストを返却
  3. saveAction - 指定したゲームのアクションを保存
  4. queryActions - ゲームに関連する全アクションのページネーション付きリストを返却

APIスキーマ

APIの入力と出力を定義するため、packages/game-api/schema/srcプロジェクト内でZodを使用してスキーマを作成します:

import { z } from 'zod';
export const ActionSchema = z.object({
playerName: z.string(),
timestamp: z.string().datetime(),
role: z.enum(['assistant', 'user']),
content: z.string(),
});
export type IAction = z.TypeOf<typeof ActionSchema>;

このプロジェクトで使用しないため、./procedures/echo.tsファイルは削除できます。

エンティティモデリング

アプリケーションのER図は以下の通りです:

dungeon-adventure-er.png

DynamoDBでデータベースを実装するため、ElectroDB DynamoDBクライアントライブラリを使用して簡素化します。まず次のコマンドを実行してelectrodbをインストールします:

Terminal window
pnpm add -w electrodb @aws-sdk/client-dynamodb

上記のER図に従ってElectroDBエンティティを定義するため、packages/game-api/backend/src/entitiesフォルダ内に以下のファイルを作成します:

import { Entity } from 'electrodb';
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
export const createActionEntity = (client?: DynamoDBClient) =>
new Entity(
{
model: {
entity: 'Action',
version: '1',
service: 'game',
},
attributes: {
playerName: { type: 'string', required: true, readOnly: true },
timestamp: {
type: 'string',
required: true,
readOnly: true,
set: () => new Date().toISOString(),
default: () => new Date().toISOString(),
},
role: { type: 'string', required: true, readOnly: true },
content: { type: 'string', required: true, readOnly: true },
},
indexes: {
primary: {
pk: { field: 'pk', composite: ['playerName'] },
sk: { field: 'sk', composite: ['timestamp'] },
},
},
},
{ client, table: process.env.TABLE_NAME },
);

ElectroDBは非常に強力で、型定義だけでなくタイムスタンプなどのデフォルト値も設定できます。さらにElectroDBはDynamoDB使用時のベストプラクティスであるシングルテーブル設計を採用しています。

tRPCコンテキストへのDynamoDBクライアント追加

各プロシージャでDynamoDBクライアントにアクセスする必要があるため、コンテキスト経由で渡せるクライアントの単一インスタンスを作成します。これを行うため、packages/game-api/backend/src内で以下の変更を加えます:

middleware/dynamodb.ts
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import { initTRPC } from '@trpc/server';
export interface IDynamoDBContext {
dynamoDb?: DynamoDBClient;
}
export const createDynamoDBPlugin = () => {
const t = initTRPC.context<IDynamoDBContext>().create();
return t.procedure.use(async (opts) => {
const dynamoDb = new DynamoDBClient();
const response = await opts.next({
ctx: {
...opts.ctx,
dynamoDb,
},
});
return response;
});
};

DynamoDBClientを作成しコンテキストに注入するプラグインです。

プロシージャの定義

APIメソッドを実装します。packages/game-api/backend/src/procedures内で以下の変更を加えます:

import { createActionEntity } from '../entities/action.js';
import {
ActionSchema,
IAction,
QueryInputSchema,
createPaginatedQueryOutput,
} from ':dungeon-adventure/game-api-schema';
import { publicProcedure } from '../init.js';
import { z } from 'zod';
export const queryActions = publicProcedure
.input(QueryInputSchema.extend({ playerName: z.string() }))
.output(createPaginatedQueryOutput(ActionSchema))
.query(async ({ input, ctx }) => {
const actionEntity = createActionEntity(ctx.dynamoDb);
const result = await actionEntity.query
.primary({ playerName: input.playerName })
.go({ cursor: input.cursor, count: input.limit });
return {
items: result.data as IAction[],
cursor: result.cursor,
};
});

このプロジェクトで使用しないため、echo.tsファイル(packages/game-api/backend/src/procedures内)は削除できます。

ルーター設定

プロシージャをAPIに接続します。以下のファイルを更新します:

packages/game-api/backend/src/router.ts
import {
awsLambdaRequestHandler,
CreateAWSLambdaContextOptions,
} from '@trpc/server/adapters/aws-lambda';
import { echo } from './procedures/echo.js';
import { t } from './init.js';
import { APIGatewayProxyEvent } from 'aws-lambda';
import { queryActions } from './procedures/query-actions.js';
import { saveAction } from './procedures/save-action.js';
import { queryGames } from './procedures/query-games.js';
import { saveGame } from './procedures/save-game.js';
export const router = t.router;
export const appRouter = router({
echo,
actions: router({
query: queryActions,
save: saveAction,
}),
games: router({
query: queryGames,
save: saveGame,
}),
});
export const handler = awsLambdaRequestHandler({
router: appRouter,
createContext: (
ctx: CreateAWSLambdaContextOptions<APIGatewayProxyEvent>,
) => ctx,
responseMeta: () => ({
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': '*',
},
}),
});
export type AppRouter = typeof appRouter;

インフラストラクチャ

最後にDynamoDBテーブルを作成し、Game APIから操作権限を付与するためインフラを更新します。packages/infra/srcを以下のように更新します:

constructs/electrodb-table.ts
import { CfnOutput } from 'aws-cdk-lib';
import {
AttributeType,
BillingMode,
ProjectionType,
Table,
TableProps,
} from 'aws-cdk-lib/aws-dynamodb';
import { Construct } from 'constructs';
export type ElectrodbDynamoTableProps = Omit<
TableProps,
'partitionKey' | 'sortKey' | 'billingMode'
>;
export class ElectrodbDynamoTable extends Table {
constructor(scope: Construct, id: string, props?: ElectrodbDynamoTableProps) {
super(scope, id, {
partitionKey: {
name: 'pk',
type: AttributeType.STRING,
},
sortKey: {
name: 'sk',
type: AttributeType.STRING,
},
billingMode: BillingMode.PAY_PER_REQUEST,
...props,
});
this.addGlobalSecondaryIndex({
indexName: 'gsi1pk-gsi1sk-index',
partitionKey: {
name: 'gsi1pk',
type: AttributeType.STRING,
},
sortKey: {
name: 'gsi1sk',
type: AttributeType.STRING,
},
projectionType: ProjectionType.ALL,
});
new CfnOutput(this, 'TableName', { value: this.tableName });
}
}

デプロイとテスト

まずコードベースをビルドします:

Terminal window
pnpm nx run-many --target build --all

次のコマンドでアプリケーションをデプロイできます:

Terminal window
pnpm nx run @dungeon-adventure/infra:deploy dungeon-adventure-infra-sandbox

初回デプロイは約8分かかります。以降のデプロイは約2分です。

全スタックを一括デプロイする方法はこちら

デプロイ完了後、以下のような出力が表示されます(一部値は編集済み):

Terminal window
dungeon-adventure-infra-sandbox
dungeon-adventure-infra-sandbox: deploying... [2/2]
dungeon-adventure-infra-sandbox
Deployment time: 354s
Outputs:
dungeon-adventure-infra-sandbox.ElectroDbTableTableNameXXX = dungeon-adventure-infra-sandbox-ElectroDbTableXXX-YYY
dungeon-adventure-infra-sandbox.GameApiEndpointXXX = https://xxx.execute-api.region.amazonaws.com/prod/
dungeon-adventure-infra-sandbox.GameUIDistributionDomainNameXXX = xxx.cloudfront.net
dungeon-adventure-infra-sandbox.StoryApiEndpointXXX = https://xxx.execute-api.region.amazonaws.com/prod/
dungeon-adventure-infra-sandbox.UserIdentityUserIdentityIdentityPoolIdXXX = region:xxx
dungeon-adventure-infra-sandbox.UserIdentityUserIdentityUserPoolIdXXX = region_xxx

APIは以下の方法でテストできます:

  • tRPCバックエンドのローカルインスタンスを起動し、curlでAPIを呼び出す
  • デプロイ済みAPIをsigv4対応curlで呼び出す

次のコマンドでgame-apiサーバーを起動:

Terminal window
TABLE_NAME=dungeon-adventure-infra-sandbox-ElectroDbTableXXX-YYY pnpm nx run @dungeon-adventure/game-api:serve

サーバー起動後、次のコマンドで呼び出せます:

Terminal window
curl -X GET 'http://localhost:2022/games.query?input=%7B%7D'

コマンドが成功すると、以下のようなレスポンスが返ります:

{"result":{"data":{"items":[],"cursor":null}}}

おめでとうございます!tRPCを使用した最初のAPIの構築とデプロイに成功しました! 🎉🎉🎉