타입스크립트 람다 함수
TypeScript Lambda Function 생성기는 기존 TypeScript 프로젝트에 람다 함수를 추가할 수 있는 기능을 제공합니다.
이 생성기는 AWS CDK 인프라 설정과 함께 새로운 TypeScript 람다 핸들러를 생성합니다. 생성된 핸들러는 AWS Lambda Powertools for TypeScript를 사용하여 로깅, AWS X-Ray 추적, CloudWatch 메트릭 등의 관측 기능과 AWS Lambda Powertools의 Parser를 통한 이벤트 유형 안전성을 제공합니다.
사용 방법
섹션 제목: “사용 방법”TypeScript 람다 함수 생성
섹션 제목: “TypeScript 람다 함수 생성”두 가지 방법으로 람다 함수를 생성할 수 있습니다:
- 설치 Nx Console VSCode Plugin 아직 설치하지 않았다면
- VSCode에서 Nx 콘솔 열기
- 클릭
Generate (UI)
"Common Nx Commands" 섹션에서 - 검색
@aws/nx-plugin - ts#lambda-function
- 필수 매개변수 입력
- 클릭
Generate
pnpm nx g @aws/nx-plugin:ts#lambda-function
yarn nx g @aws/nx-plugin:ts#lambda-function
npx nx g @aws/nx-plugin:ts#lambda-function
bunx nx g @aws/nx-plugin:ts#lambda-function
어떤 파일이 변경될지 확인하기 위해 드라이 런을 수행할 수도 있습니다
pnpm nx g @aws/nx-plugin:ts#lambda-function --dry-run
yarn nx g @aws/nx-plugin:ts#lambda-function --dry-run
npx nx g @aws/nx-plugin:ts#lambda-function --dry-run
bunx nx g @aws/nx-plugin:ts#lambda-function --dry-run
매개변수 | 타입 | 기본값 | 설명 |
---|---|---|---|
project 필수 | string | - | The project to add the lambda function to |
functionName 필수 | string | - | The name of the function to add |
functionPath | string | - | Optional subdirectory within the project source directory to add the function to |
eventSource | string | Any | Optional event source schema to use for the lambda function |
생성기 출력 결과
섹션 제목: “생성기 출력 결과”생성기는 프로젝트에 다음 파일들을 추가합니다:
디렉터리<project-name>
디렉터리src/
- <lambda-function>.ts 함수 구현체
생성기는 또한 packages/common/constructs/src/app/lambda-functions
디렉토리에 배포용 CDK 구문을 생성합니다.
functionPath
옵션이 제공된 경우, 생성기는 프로젝트 소스 디렉토리 내 지정된 경로에 핸들러를 추가합니다:
디렉터리<project-name>
디렉터리src/
디렉터리<custom-path>/
- <function-name>.ts 함수 구현체
함수 구현
섹션 제목: “함수 구현”주요 함수 구현은 <function-name>.ts
에 위치합니다. 예시:
import { parser } from '@aws-lambda-powertools/parser/middleware';import { EventBridgeSchema } from '@aws-lambda-powertools/parser/schemas';import middy from '@middy/core';import { Tracer } from '@aws-lambda-powertools/tracer';import { captureLambdaHandler } from '@aws-lambda-powertools/tracer/middleware';import { injectLambdaContext } from '@aws-lambda-powertools/logger/middleware';import { Logger } from '@aws-lambda-powertools/logger';import { Metrics } from '@aws-lambda-powertools/metrics';import { logMetrics } from '@aws-lambda-powertools/metrics/middleware';import { z } from 'zod';
process.env.POWERTOOLS_METRICS_NAMESPACE = 'MyFunction';process.env.POWERTOOLS_SERVICE_NAME = 'MyFunction';
const tracer = new Tracer();const logger = new Logger();const metrics = new Metrics();
export const myFunction = async ( event: z.infer<typeof EventBridgeSchema>,): Promise<void> => { logger.info('Received event', event);
// TODO: 구현 필요};
export const handler = middy() .use(captureLambdaHandler(tracer)) .use(injectLambdaContext(logger)) .use(logMetrics(metrics)) .use(parser({ schema: EventBridgeSchema })) .handler(myFunction);
생성기는 자동으로 다음 기능들을 설정합니다:
- 향상된 람다 기능을 위한 Middy 미들웨어 스택
- 관측성을 위한 AWS Lambda Powertools 통합
- CloudWatch를 통한 메트릭 수집
- 파서 미들웨어를 사용한 유형 안전성
- 최적화된 배포 패키지를 위한 esbuild 번들링
AWS Lambda Powertools를 통한 관측성
섹션 제목: “AWS Lambda Powertools를 통한 관측성”생성기는 Middy 미들웨어를 통해 자동 컨텍스트 주입이 가능한 AWS Lambda Powertools 구조화 로깅을 구성합니다.
export const handler = middy() .use(injectLambdaContext(logger)) .handler(myFunction);
AWS X-Ray 추적은 captureLambdaHandler
미들웨어를 통해 자동 구성됩니다. 커스텀 서브세그먼트 추가 가능:
const tracer = new Tracer();
export const myFunction = async ( event: z.infer<typeof EventBridgeSchema>,): Promise<void> => { // 새 서브세그먼트 생성 const subsegment = tracer.getSegment()?.addNewSubsegment('custom-operation'); try { // 사용자 로직 } catch (error) { subsegment?.addError(error as Error); throw error; } finally { subsegment?.close(); }};
export const handler = middy() .use(captureLambdaHandler(tracer)) .handler(myFunction);
메트릭
섹션 제목: “메트릭”logMetrics
미들웨어를 통해 요청별 CloudWatch 메트릭 자동 수집. 커스텀 메트릭 추가 가능:
const metrics = new Metrics();
export const myFunction = async ( event: z.infer<typeof EventBridgeSchema>,): Promise<void> => { metrics.addMetric("CustomMetric", MetricUnit.Count, 1); metrics.addMetric("ProcessingTime", MetricUnit.Milliseconds, processingTime);};
export const handler = middy() .use(logMetrics(metrics)) .handler(myFunction);
유형 안전성
섹션 제목: “유형 안전성”람다 함수 생성 시 eventSource
를 선택한 경우, AWS Lambda Powertools의 parser
미들웨어가 자동 구성됩니다.
export const myFunction = async ( event: z.infer<typeof EventBridgeSchema>,): Promise<void> => { event.detail // <- IDE 자동완성 지원되는 유형 안전 접근};
export const handler = middy() .use(parser({ schema: EventBridgeSchema })) .handler(myFunction);
이를 통해 컴파일 타임 유형 안전성과 런타임 이벤트 유효성 검증이 제공됩니다.
이벤트 유형을 지정하지 않으려면 eventSource
에 Any
를 선택하면 이벤트 매개변수가 any
유형으로 설정됩니다.
번들링
섹션 제목: “번들링”생성기는 최적화된 람다 배포 패키지를 위해 esbuild를 자동 구성합니다:
특정 람다 함수 번들링:
pnpm nx run <project-name>:bundle-<function-name>
yarn nx run <project-name>:bundle-<function-name>
npx nx run <project-name>:bundle-<function-name>
bunx nx run <project-name>:bundle-<function-name>
프로젝트 내 모든 람다 함수 번들링:
pnpm nx run <project-name>:bundle
yarn nx run <project-name>:bundle
npx nx run <project-name>:bundle
bunx nx run <project-name>:bundle
함수 배포
섹션 제목: “함수 배포”TypeScript Lambda Function 생성기는 common/constructs
폴더에 배포용 CDK 구문을 생성합니다. CDK 애플리케이션에서 사용 가능:
import { MyProjectMyFunction } from ':my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { // 스택에 함수 추가 const fn = new MyProjectMyFunction(this, 'MyFunction'); }}
이 설정에는 다음이 포함됩니다:
- AWS Lambda 함수
- CloudWatch 로그 그룹
- X-Ray 추적 구성
- CloudWatch 메트릭 네임스페이스
이 함수는 모든 람다 이벤트 소스의 대상으로 사용 가능:
다음 예제는 EventBridge 스케줄을 사용하여 람다 함수를 주기적으로 실행하는 CDK 코드를 보여줍니다:
import { Rule, Schedule } from 'aws-cdk-lib/aws-events';import { LambdaFunction } from 'aws-cdk-lib/aws-events-targets';import { MyProjectMyFunction } from ':my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { // 스택에 함수 추가 const fn = new MyProjectMyFunction(this, 'MyFunction');
// EventBridge 스케줄 규칙에 함수 추가 const eventRule = new Rule(this, 'MyFunctionScheduleRule', { schedule: Schedule.cron({ minute: '15' }), targets: [new LambdaFunction(fn)], }); }}