본문으로 건너뛰기
버전: 11.x

AWS Lambda + API Gateway 어댑터

AWS Lambda 어댑터

AWS Lambda 어댑터는 API Gateway REST API(v1)HTTP API(v2), 그리고 Lambda Function URL 사용 사례를 지원합니다.

httpBatchLink는 단일 API Gateway 리소스에서 라우터가 작동하도록 요구합니다(예시 참조). 프로시저별로 리소스를 구성하려면 httpLink를 대신 사용할 수 있습니다(자세한 정보).

예제 앱

설명링크
NodeJS 클라이언트를 사용한 API Gateway.
응답 스트리밍을 지원하는 API Gateway REST API.

tRPC 추가 방법

1. 의존성 설치

bash
yarn add @trpc/server
bash
yarn add @trpc/server
AI 에이전트

AI 코딩 에이전트를 사용하는 경우, 더 나은 코드 생성을 위해 tRPC 스킬을 설치하세요:

bash
npx @tanstack/intent@latest install
bash
npx @tanstack/intent@latest install

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 type { APIGatewayProxyEventV2 } from 'aws-lambda';
import type { CreateAWSLambdaContextOptions } from '@trpc/server/adapters/aws-lambda';
import { awsLambdaRequestHandler } from '@trpc/server/adapters/aws-lambda';
import { appRouter } from './router';
 
// 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 type { APIGatewayProxyEventV2 } from 'aws-lambda';
import type { CreateAWSLambdaContextOptions } from '@trpc/server/adapters/aws-lambda';
import { awsLambdaRequestHandler } from '@trpc/server/adapters/aws-lambda';
import { appRouter } from './router';
 
// 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을 사용하여 함수를 호출하세요.

엔드포인트HTTP URI
getUserGET https://<execution-api-link>/getUser?input=INPUT

여기서 INPUT은 URI 인코딩된 JSON 문자열입니다.

페이로드 형식 버전에 대해

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 응답 스트리밍에 대해 자세히 알아보기.

응답 스트리밍

스트리밍 핸들러의 시그니처는 기본 핸들러와 다릅니다. 스트리밍 핸들러는 기본 node 핸들러 매개변수인 eventcontext 외에도 쓰기 가능한 스트림 매개변수인 responseStream을 추가로 수신합니다. Lambda가 응답을 스트리밍하도록 하려면 함수 핸들러를 awslambda.streamifyResponse() 데코레이터로 감싸야 합니다.

awslambda 네임스페이스는 Lambda 실행 환경에 의해 자동으로 제공됩니다. @types/aws-lambda에서 타입을 가져와서 awslambda 네임스페이스로 전역 네임스페이스를 확장할 수 있습니다.

server.ts
ts
/// <reference types="aws-lambda" />
import type { APIGatewayProxyEventV2 } from 'aws-lambda';
import type { CreateAWSLambdaContextOptions } from '@trpc/server/adapters/aws-lambda';
import { awsLambdaStreamingRequestHandler } from '@trpc/server/adapters/aws-lambda';
import { appRouter } from './router';
 
// created for each request
const createContext = ({
event,
context,
}: CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>) => ({
// your context
});
type Context = Awaited<ReturnType<typeof createContext>>;
 
export const handler = awslambda.streamifyResponse(
awsLambdaStreamingRequestHandler({
router: appRouter,
createContext,
}),
);
server.ts
ts
/// <reference types="aws-lambda" />
import type { APIGatewayProxyEventV2 } from 'aws-lambda';
import type { CreateAWSLambdaContextOptions } from '@trpc/server/adapters/aws-lambda';
import { awsLambdaStreamingRequestHandler } from '@trpc/server/adapters/aws-lambda';
import { appRouter } from './router';
 
// created for each request
const createContext = ({
event,
context,
}: CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>) => ({
// your context
});
type Context = Awaited<ReturnType<typeof createContext>>;
 
export const handler = awslambda.streamifyResponse(
awsLambdaStreamingRequestHandler({
router: appRouter,
createContext,
}),
);