AWS Lambda + API Gateway アダプター
非公式ベータ版翻訳
このページは PageTurner AI で翻訳されました(ベータ版)。プロジェクト公式の承認はありません。 エラーを見つけましたか? 問題を報告 →
AWS Lambda アダプター
AWS Lambda アダプターは、API Gateway Rest API (v1) および HTTP API (v2) のユースケースでサポートされています。
サンプルアプリケーション
| Description | Links |
|---|---|
| API Gateway with NodeJS client. |
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 を使用して関数を呼び出せます。
| Endpoint | HTTP URI |
|---|---|
getUser | GET https://<execution-api-link>/getUser?input=INPUT where INPUT is a URI-encoded JSON string. |
ペイロードフォーマットバージョンについて
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>