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

API Gateway 経由での Amazon Lambda 使用方法

非公式ベータ版翻訳

このページは PageTurner AI で翻訳されました(ベータ版)。プロジェクト公式の承認はありません。 エラーを見つけましたか? 問題を報告 →

Amazon Lambda アダプター

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

サンプルアプリケーション

DescriptionURLLinks
API Gateway with NodeJS client.n/a

tRPC の追加方法

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

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

2. tRPCルーターの作成

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

server.ts
ts
import * as trpc from '@trpc/server';
import { z } from 'zod';
const appRouter = trpc.router().query('getUser', {
input: z.string(),
async resolve(req) {
req.input; // string
return { id: req.input, name: 'Bilbo' };
},
});
// export type definition of API
export type AppRouter = typeof appRouter;
server.ts
ts
import * as trpc from '@trpc/server';
import { z } from 'zod';
const appRouter = trpc.router().query('getUser', {
input: z.string(),
async resolve(req) {
req.input; // string
return { id: req.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) => ({}) // no context
type Context = trpc.inferAsyncReturnType<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) => ({}) // no context
type Context = trpc.inferAsyncReturnType<typeof createContext>;
export const handler = awsLambdaRequestHandler({
router: appRouter,
createContext,
})

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

EndpointHTTP URI
getUserGET 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>

ペイロードフォーマットバージョンの詳細はこちら