API Gateway를 통한 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 Gateway 어댑터 사용
tRPC에는 기본 제공되는 API Gateway 어댑터가 포함되어 있습니다. 이 어댑터를 사용하면 라우트를 API Gateway 핸들러를 통해 실행할 수 있습니다.
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 Gateway URL을 사용해 함수를 호출하세요.
| Endpoint | HTTP URI |
|---|---|
getUser | GET 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
사용 중인 버전을 확인하려면 다음과 같이 컨텍스트를 제공하세요:
function createContext({ event, context, }: CreateAWSLambdaContextOptions<APIGatewayProxyEvent>) { ... } // CreateAWSLambdaContextOptions<APIGatewayProxyEvent> or CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>
function createContext({ event, context, }: CreateAWSLambdaContextOptions<APIGatewayProxyEvent>) { ... } // CreateAWSLambdaContextOptions<APIGatewayProxyEvent> or CreateAWSLambdaContextOptions<APIGatewayProxyEventV2>