AWS Lambda + API Gateway アダプター
AWS Lambda アダプター
AWS Lambda アダプターは、API Gateway Rest API (v1) および HTTP API (v2) のユースケースでサポートされています。
サンプルアプリ
| 説明 | リンク |
|---|---|
| NodeJS クライアントを使用した API Gateway。 |
tRPC を追加する方法
1. 依存関係のインストール
bashyarn add @trpc/server
bashyarn add @trpc/server
2. tRPC ルーターの作成
tRPC ルーターを実装します。サンプルルーターを以下に示します。
server.tstsimport { initTRPC } from '@trpc/server';import { z } from 'zod';export const t = initTRPC.create();const appRouter = t.router({getUser: t.procedure.input(z.string()).query((opts) => {opts.input; // stringreturn { id: opts.input, name: 'Bilbo' };}),});// export type definition of APIexport type AppRouter = typeof appRouter;
server.tstsimport { initTRPC } from '@trpc/server';import { z } from 'zod';export const t = initTRPC.create();const appRouter = t.router({getUser: t.procedure.input(z.string()).query((opts) => {opts.input; // stringreturn { id: opts.input, name: 'Bilbo' };}),});// export type definition of APIexport type AppRouter = typeof appRouter;
3. Amazon API Gateway アダプターの使用
tRPC には、API Gateway 用のアダプターが標準で含まれています。このアダプターを使用すると、API Gateway ハンドラーを介してルートを実行できます。
server.tstsimport { CreateAWSLambdaContextOptions, awsLambdaRequestHandler } from '@trpc/server/adapters/aws-lambda';const appRouter = /* ... */;// created for each requestconst createContext = ({event,context,}: CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>) => ({}) // no contexttype Context = Awaited<ReturnType<typeof createContext>>;export const handler = awsLambdaRequestHandler({router: appRouter,createContext,})
server.tstsimport { CreateAWSLambdaContextOptions, awsLambdaRequestHandler } from '@trpc/server/adapters/aws-lambda';const appRouter = /* ... */;// created for each requestconst createContext = ({event,context,}: CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>) => ({}) // no contexttype Context = Awaited<ReturnType<typeof createContext>>;export const handler = awsLambdaRequestHandler({router: appRouter,createContext,})
コードをビルドしてデプロイし、API Gateway URL を使用して関数を呼び出します。
| エンドポイント | HTTP URI |
|---|---|
getUser | GET https://<execution-api-link>/getUser?input=INPUT ここで、 INPUT は URI エンコードされた JSON 文字列です。 |
ペイロード形式バージョンについて
API Gateway が Lambda を呼び出す際には、2 つの異なるイベントデータ形式があります。REST API の場合はバージョン "1.0" (APIGatewayProxyEvent) にする必要がありますが、HTTP API の場合はバージョン "1.0" または "2.0" を指定して選択できます。
- バージョン 1.0:
APIGatewayProxyEvent - バージョン 2.0:
APIGatewayProxyEventV2
どのようなバージョンであるかを推測するには、次のようにコンテキストを指定します。
tsfunction createContext({event,context,}: CreateAWSLambdaContextOptions<APIGatewayProxyEvent>) {...}// CreateAWSLambdaContextOptions<APIGatewayProxyEvent> or CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>
tsfunction createContext({event,context,}: CreateAWSLambdaContextOptions<APIGatewayProxyEvent>) {...}// CreateAWSLambdaContextOptions<APIGatewayProxyEvent> or CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>