跳至主内容
版本:11.x

AWS Lambda + API Gateway 适配器

非官方测试版翻译

本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →

AWS Lambda 适配器

该适配器支持 API Gateway REST API(v1)HTTP API(v2)Lambda Function URL 使用场景。

httpBatchLink 要求路由器在单个 API Gateway 资源上运行(如示例所示)。 若需为每个过程创建独立资源,可使用 httpLink更多信息)。

示例应用

DescriptionLinks
API Gateway with NodeJS client.
API Gateway REST API with response streaming.

如何添加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网关适配器

tRPC开箱即用地包含了一个API网关适配器。此适配器允许你通过API网关处理程序运行你的路由。

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网关URL来调用你的函数。

EndpointHTTP URI
getUserGET https://<execution-api-link>/getUser?input=INPUT

where INPUT is a URI-encoded JSON string.

关于负载格式版本的说明

API Gateway 在调用 Lambda 时有两种不同的事件数据格式。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>

在此处阅读有关负载格式版本的更多信息

AWS Lambda 响应流适配器

AWS Lambda 支持通过 Lambda Function URL 和 API Gateway REST API 向客户端流式传输响应。

响应流式传输支持 Lambda Function URL 和 API Gateway REST API。对于 API Gateway REST API,需配置集成设置 responseTransferMode: STREAM阅读有关 Lambda 响应流式传输的更多信息以及API Gateway 响应流式传输

示例应用

DescriptionLinks
Lambda Function URL with NodeJS client.
API Gateway REST API with response streaming.

响应流

流式处理函数的签名与默认处理函数不同。除默认的节点处理函数参数 eventcontext 外,流式处理函数还额外接收一个可写流参数 responseStream。要指示 Lambda 流式传输响应,必须用 awslambda.streamifyResponse() 装饰器包装你的函数处理程序。

注意:awslambda 命名空间由 Lambda 执行环境自动提供,可通过 @types/aws-lambda 导入类型,从而使用 awslambda 命名空间扩展全局命名空间。

server.ts
ts
import { awsLambdaStreamingRequestHandler } from '@trpc/server/adapters/aws-lambda';
import type { StreamifyHandler } from 'aws-lambda';
const appRouter = router({
iterable: publicProcedure.query(async function* () {
for (let i = 0; i < 10; i++) {
await new Promise((resolve) => setTimeout(resolve, 500));
yield i;
}
}),
});
export const handler = awslambda.streamifyResponse(
awsLambdaStreamingRequestHandler({
router: appRouter,
/* ... */
}),
);
server.ts
ts
import { awsLambdaStreamingRequestHandler } from '@trpc/server/adapters/aws-lambda';
import type { StreamifyHandler } from 'aws-lambda';
const appRouter = router({
iterable: publicProcedure.query(async function* () {
for (let i = 0; i < 10; i++) {
await new Promise((resolve) => setTimeout(resolve, 500));
yield i;
}
}),
});
export const handler = awslambda.streamifyResponse(
awsLambdaStreamingRequestHandler({
router: appRouter,
/* ... */
}),
);