AWS Lambda + API 网关适配器
AWS Lambda 适配器
¥AWS Lambda adapter
AWS Lambda 适配器支持 API 网关 REST API(v1)、HTTP API(v2) 和 Lambda 函数 URL 用例。
¥The AWS Lambda adapter is supported for API Gateway REST API(v1) and HTTP API(v2), and Lambda Function URL use cases.
httpBatchLink
要求路由在单个 API 网关资源上工作(如 示例 中所示)。如果你希望每个过程都有一个资源,则可以改用httpLink
(更多信息)。¥
httpBatchLink
requires the router to work on a single API Gateway Resource (as shown in the example). If you'd like to have a Resource per procedure, you can use thehttpLink
instead (more info).
示例应用
¥Example app
描述 | 链接 |
---|---|
带有 NodeJS 客户端的 API 网关。 |
如何添加 tRPC
¥How to add tRPC
1. 安装依赖
¥ Install deps
bash
yarn add @trpc/server
bash
yarn add @trpc/server
2. 创建 tRPC 路由
¥ Create a tRPC router
实现你的 tRPC 路由。下面给出了一个示例路由:
¥Implement your tRPC router. A sample router is given below:
server.tsts
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; // stringreturn { id: opts.input, name: 'Bilbo' };}),});// export type definition of APIexport type AppRouter = typeof appRouter;
server.tsts
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; // stringreturn { id: opts.input, name: 'Bilbo' };}),});// export type definition of APIexport type AppRouter = typeof appRouter;
3. 使用 Amazon API Gateway 适配器
¥ Use the Amazon API Gateway adapter
tRPC 包含一个开箱即用的 API 网关适配器。该适配器允许你通过 API 网关处理程序运行路由。
¥tRPC includes an adapter for API Gateway out of the box. This adapter lets you run your routes through the API Gateway handler.
server.tsts
import { 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.tsts
import { 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 网关 URL 来调用你的函数。
¥Build & deploy your code, now use your API Gateway URL to call your function.
端点 | HTTP URI |
---|---|
getUser | GET https://<execution-api-link>/getUser?input=INPUT 其中 INPUT 是 URI 编码的 JSON 字符串。 |
关于有效负载格式版本的说明
¥A word about payload format version
API Gateway 在调用 Lambda 时有两种不同的事件数据格式。对于 REST API,它们应该是版本 "1.0"(APIGatewayProxyEvent
),但你可以通过声明版本 "1.0" 或 "2.0" 来选择对于 HTTP API 的版本。
¥API Gateway has two different event data formats when it invokes a Lambda. For REST APIs they should be version "1.0"(APIGatewayProxyEvent
), but you can choose which for HTTP APIs by stating either version "1.0" or "2.0".
-
1.0 版本:
APIGatewayProxyEvent
¥Version 1.0:
APIGatewayProxyEvent
-
2.0 版本:
APIGatewayProxyEventV2
¥Version 2.0:
APIGatewayProxyEventV2
要推断你可能拥有的版本,请提供以下上下文:
¥To infer what version you might have, supply the context as following:
ts
function createContext({event,context,}: CreateAWSLambdaContextOptions<APIGatewayProxyEvent>) {...}// CreateAWSLambdaContextOptions<APIGatewayProxyEvent> or CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>
ts
function createContext({event,context,}: CreateAWSLambdaContextOptions<APIGatewayProxyEvent>) {...}// CreateAWSLambdaContextOptions<APIGatewayProxyEvent> or CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>
¥Read more here about payload format version
AWS Lambda 响应流适配器
¥AWS Lambda Response Streaming Adapter
AWS Lambda 支持以流方式响应客户端。
¥AWS Lambda supports streaming responses to clients.
响应流仅支持 Lambda 函数 URL。你不能使用 API 网关来流式传输响应。点击此处了解更多关于响应流的信息。
¥Response streaming is only supported for Lambda Function URLs. You can not use API Gateway to stream responses. Read more here about response streaming.
示例应用
¥Example app
描述 | 链接 |
---|---|
使用 NodeJS 客户端的 Lambda 函数 URL。 |
响应流
¥Response Streaming
流式处理程序的签名与默认处理程序不同。除了默认节点处理程序参数 event
和 context
之外,流式处理程序还接收一个可写的流参数 responseStream
。要指示 Lambda 应该流式传输你的响应,你必须使用 awslambda.streamifyResponse()
装饰器封装你的函数处理程序。
¥The signature of a streaming handler is different from the default handler. The streaming handler additonally receives a writable stream parameter, responseStream
, besides the default node handler parameters, event
and context
. To indicate that Lambda should stream your responses, you must wrap your function handler with the awslambda.streamifyResponse()
decorator.
请注意,
awslambda
命名空间由 Lambda 执行环境自动提供。你可以导入@types/aws-lambda
中的类型,以便使用awslambda
命名空间扩充全局命名空间。¥Note that the
awslambda
namespace is automatically provided by the Lambda execution environment. You can import the types from@types/aws-lambda
to augment the global namespace with theawslambda
namespace.
server.tsts
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.tsts
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,/* ... */}),);