API Gateway 経由での Amazon Lambda 使用方法
非公式ベータ版翻訳
このページは PageTurner AI で翻訳されました(ベータ版)。プロジェクト公式の承認はありません。 エラーを見つけましたか? 問題を報告 →
Amazon Lambda アダプター
AWS Lambda アダプターは、API Gateway Rest API (v1) および HTTP API (v2) のユースケースでサポートされています。
サンプルアプリケーション
| Description | URL | Links |
|---|---|---|
| API Gateway with NodeJS client. | n/a |
tRPC の追加方法
1. 依存関係のインストール
bashyarn add @trpc/server
bashyarn add @trpc/server
2. tRPCルーターの作成
tRPC ルーターを実装します。以下にサンプルルーターを示します:
server.tstsimport * as trpc from '@trpc/server';import { z } from 'zod';const appRouter = trpc.router().query('getUser', {input: z.string(),async resolve(req) {req.input; // stringreturn { id: req.input, name: 'Bilbo' };},});// export type definition of APIexport type AppRouter = typeof appRouter;
server.tstsimport * as trpc from '@trpc/server';import { z } from 'zod';const appRouter = trpc.router().query('getUser', {input: z.string(),async resolve(req) {req.input; // stringreturn { id: req.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) => ({}) // no contexttype Context = trpc.inferAsyncReturnType<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) => ({}) // no contexttype Context = trpc.inferAsyncReturnType<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
使用されているバージョンを判別するには、以下のようにコンテキストを指定します:
function createContext({ event, context, }: CreateAWSLambdaContextOptions<APIGatewayProxyEvent>) { ... } // CreateAWSLambdaContextOptions<APIGatewayProxyEvent> or CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>
function createContext({ event, context, }: CreateAWSLambdaContextOptions<APIGatewayProxyEvent>) { ... } // CreateAWSLambdaContextOptions<APIGatewayProxyEvent> or CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>