メインコンテンツにスキップ
バージョン: 11.x

AWS Lambda + API Gateway アダプター

AWS Lambda アダプター

AWS Lambda アダプターは、API Gateway Rest API (v1) および HTTP API (v2) のユースケースでサポートされています。

サンプルアプリ

説明リンク
NodeJS クライアントを使用した API Gateway。

tRPC を追加する方法

1. 依存関係のインストール

bash
yarn add @trpc/server
bash
yarn add @trpc/server

2. tRPC ルーターの作成

tRPC ルーターを実装します。サンプルルーターを以下に示します。

server.ts
ts
import { 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; // string
return { id: opts.input, name: 'Bilbo' };
}),
});
// export type definition of API
export type AppRouter = typeof appRouter;
server.ts
ts
import { 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; // string
return { id: opts.input, name: 'Bilbo' };
}),
});
// export type definition of API
export type AppRouter = typeof appRouter;

3. Amazon API Gateway アダプターの使用

tRPC には、API Gateway 用のアダプターが標準で含まれています。このアダプターを使用すると、API Gateway ハンドラーを介してルートを実行できます。

server.ts
ts
import { CreateAWSLambdaContextOptions, awsLambdaRequestHandler } from '@trpc/server/adapters/aws-lambda';
const appRouter = /* ... */;
// created for each request
const createContext = ({
event,
context,
}: CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>) => ({}) // no context
type Context = Awaited<ReturnType<typeof createContext>>;
export const handler = awsLambdaRequestHandler({
router: appRouter,
createContext,
})
server.ts
ts
import { CreateAWSLambdaContextOptions, awsLambdaRequestHandler } from '@trpc/server/adapters/aws-lambda';
const appRouter = /* ... */;
// created for each request
const createContext = ({
event,
context,
}: CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>) => ({}) // no context
type Context = Awaited<ReturnType<typeof createContext>>;
export const handler = awsLambdaRequestHandler({
router: appRouter,
createContext,
})

コードをビルドしてデプロイし、API Gateway URL を使用して関数を呼び出します。

エンドポイントHTTP URI
getUserGET 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

どのようなバージョンであるかを推測するには、次のようにコンテキストを指定します。

ts
function createContext({
event,
context,
}: CreateAWSLambdaContextOptions<APIGatewayProxyEvent>) {
...
}
// CreateAWSLambdaContextOptions<APIGatewayProxyEvent> or CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>
ts
function createContext({
event,
context,
}: CreateAWSLambdaContextOptions<APIGatewayProxyEvent>) {
...
}
// CreateAWSLambdaContextOptions<APIGatewayProxyEvent> or CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>

ペイロード形式バージョンの詳細はこちらをご覧ください