콘텐츠로 이동

타입스크립트 람다 함수

TypeScript Lambda Function 생성기는 기존 TypeScript 프로젝트에 람다 함수를 추가할 수 있는 기능을 제공합니다.

이 생성기는 AWS CDK 또는 Terraform 인프라 설정과 함께 새로운 TypeScript 람다 핸들러를 생성합니다. 생성된 핸들러는 AWS Lambda Powertools for TypeScript를 사용하여 로깅, AWS X-Ray 추적, CloudWatch 메트릭과 같은 관측 가능성을 제공하며, AWS Lambda Powertools의 Parser를 통해 이벤트에 대한 타입 안전성도 선택적으로 제공합니다.

다음 두 가지 방법으로 람다 함수를 생성할 수 있습니다:

  1. 설치 Nx Console VSCode Plugin 아직 설치하지 않았다면
  2. VSCode에서 Nx 콘솔 열기
  3. 클릭 Generate (UI) "Common Nx Commands" 섹션에서
  4. 검색 @aws/nx-plugin - ts#lambda-function
  5. 필수 매개변수 입력
    • 클릭 Generate
    매개변수 타입 기본값 설명
    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
    iacProvider string Inherit The preferred IaC provider. By default this is inherited from your initial selection.

    생성기는 프로젝트에 다음 파일들을 추가합니다:

    • 디렉터리<project-name>
      • 디렉터리src/
        • <lambda-function>.ts 함수 구현

    functionPath 옵션이 제공된 경우, 생성기는 프로젝트 소스 디렉토리 내 지정된 경로에 핸들러를 추가합니다:

    • 디렉터리<project-name>
      • 디렉터리src/
        • 디렉터리<custom-path>/
          • <function-name>.ts 함수 구현

    이 생성기는 선택한 iacProvider 기반으로 인프라를 코드 형태로 제공하므로, packages/common 디렉터리에 관련 CDK 구축 요소 또는 Terraform 모듈을 포함하는 프로젝트를 생성합니다.

    공통 인프라스트럭처 코드 프로젝트의 구조는 다음과 같습니다:

    • 디렉터리packages/common/constructs
      • 디렉터리src
        • 디렉터리app/ 특정 프로젝트/생성기에 종속적인 인프라를 위한 구축 요소
        • 디렉터리core/ app 내 구축 요소에서 재사용되는 일반적 구축 요소
        • index.ts app의 구축 요소를 익스포트하는 진입점
      • project.json 프로젝트 빌드 대상 및 구성

    생성기는 선택한 iacProvider 기반으로 함수 배포를 위한 인프라 코드를 생성합니다:

    생성기는 packages/common/constructs/src/app/lambda-functions 디렉토리에 위치한 CDK 구문을 생성하며, 이를 통해 함수를 배포할 수 있습니다.

    주요 함수 구현은 <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);

    생성기는 자동으로 다음과 같은 기능을 설정합니다:

    1. 향상된 Lambda 기능을 위한 Middy 미들웨어 스택
    2. 관측 가능성을 위한 AWS Lambda Powertools 통합
    3. CloudWatch를 통한 메트릭 수집
    4. 파서 미들웨어를 사용한 타입 안전성
    5. 최적화된 배포 패키지를 위한 Rolldown 번들링

    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);

    이를 통해 컴파일 타임 타입 안전성과 런타임 이벤트 유효성 검증이 제공됩니다.

    이벤트 타입을 지정하지 않으려면 eventSourceAny를 선택하면 이벤트 매개변수가 any 타입으로 설정됩니다.

    제너레이터는 Rolldown을 사용하여 배포 패키지를 생성하는 bundle 타겟을 자동으로 구성합니다:

    Terminal window
    pnpm nx run <project-name>:bundle

    Rolldown 구성은 rolldown.config.ts에서 확인할 수 있으며, 생성할 각 번들별로 엔트리가 존재합니다. 정의된 경우 Rolldown은 여러 번들을 병렬로 생성하는 작업을 관리합니다.

    이 생성기는 선택한 iacProvider 기반으로 CDK 또는 Terraform 인프라 코드를 생성합니다. 이를 통해 함수를 배포할 수 있습니다.

    이 생성자는 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');
    }
    }

    다음 리소스가 설정됩니다:

    1. AWS Lambda 함수
    2. CloudWatch 로그 그룹
    3. X-Ray 트레이싱 구성
    4. 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)],
    });
    }
    }