通过API网关在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网关适配器
tRPC开箱即用地包含了一个API网关适配器。此适配器允许你通过API网关处理程序运行你的路由。
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网关URL来调用你的函数。
| Endpoint | HTTP URI |
|---|---|
getUser | GET https://<execution-api-link>/getUser?input=INPUT where INPUT is a URI-encoded JSON string. |
关于负载格式版本的说明
当API网关调用Lambda时,有两种不同的事件数据格式。对于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>