Saltar al contenido principal
Versión: 10.x

Adaptador para AWS Lambda + API Gateway

Traducción Beta No Oficial

Esta página fue traducida por PageTurner AI (beta). No está respaldada oficialmente por el proyecto. ¿Encontraste un error? Reportar problema →

Adaptador para AWS Lambda

El adaptador de AWS Lambda es compatible con los casos de uso de API Gateway Rest API(v1) y HTTP API(v2).

Aplicación de ejemplo

DescriptionLinks
API Gateway with NodeJS client.

Cómo integrar tRPC

1. Instalar dependencias

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

2. Crear un router de tRPC

Implementa tu router de tRPC. A continuación se muestra un ejemplo de router:

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. Usa el adaptador de Amazon API Gateway

tRPC incluye un adaptador para API Gateway listo para usar. Este adaptador te permite ejecutar tus rutas a través del manejador de 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<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,
})

Compila e implementa tu código, luego usa tu URL de API Gateway para llamar a tu función.

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

where INPUT is a URI-encoded JSON string.

Nota sobre el formato de carga útil

API Gateway tiene dos formatos diferentes para los eventos al invocar una Lambda. Para REST APIs debe ser la versión "1.0" (APIGatewayProxyEvent), mientras que para HTTP APIs puedes elegir entre las versiones "1.0" o "2.0".

  • Versión 1.0: APIGatewayProxyEvent

  • Versión 2.0: APIGatewayProxyEventV2

Para determinar qué versión estás usando, proporciona el contexto de la siguiente manera:

ts
function createContext({
event,
context,
}: CreateAWSLambdaContextOptions<APIGatewayProxyEvent>) {
...
}
// CreateAWSLambdaContextOptions<APIGatewayProxyEvent> or CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>
ts
function createContext({
event,
context,
}: CreateAWSLambdaContextOptions<APIGatewayProxyEvent>) {
...
}
// CreateAWSLambdaContextOptions<APIGatewayProxyEvent> or CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>

Lee más aquí sobre el formato de carga útil