본문 바로가기
버전: 11.x

AWS Lambda + API Gateway 어댑터

비공식 베타 번역

이 페이지는 PageTurner AI로 번역되었습니다(베타). 프로젝트 공식 승인을 받지 않았습니다. 오류를 발견하셨나요? 문제 신고 →

AWS Lambda 어댑터

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 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<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 Gateway 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,
/* ... */
}),
);