Skip to content

TypeScriptのLambda関数

TypeScript Lambda Function ジェネレータは、既存のTypeScriptプロジェクトにLambda関数を追加する機能を提供します。

このジェネレータはAWS CDKインフラストラクチャ設定を含む新しいTypeScript Lambdaハンドラを作成します。生成されたハンドラは、AWS Lambda Powertools for TypeScriptを使用して、ロギング、AWS X-Rayトレーシング、CloudWatchメトリクスなどの観測可能性を実現し、AWS Lambda PowertoolsのParserを使用したイベントの型安全性(オプション)を提供します。

Lambda関数は2つの方法で生成できます:

  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

    ジェネレータはプロジェクトに以下のファイルを追加します:

    • Directory<project-name>
      • Directorysrc/
        • <lambda-function>.ts 関数実装

    また、packages/common/constructs/src/app/lambda-functionsディレクトリに関数のデプロイに使用できるCDKコンストラクトを作成します。

    functionPathオプションが指定された場合、ジェネレータはプロジェクトソースディレクトリ内の指定パスにハンドラを追加します:

    • Directory<project-name>
      • Directorysrc/
        • Directory<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);

    ジェネレータは以下の機能を自動的に設定します:

    1. 拡張Lambda機能のためのMiddyミドルウェアスタック
    2. 観測可能性のためのAWS Lambda Powertools統合
    3. CloudWatchを使ったメトリクス収集
    4. パーサーミドルウェアを使用した型安全性
    5. 最適化されたデプロイパッケージのためのesbuildバンドリング

    AWS Lambda Powertoolsによる観測可能性

    Section titled “AWS Lambda Powertoolsによる観測可能性”

    ジェネレータはMiddyミドルウェアを使用した自動コンテキスト注入で、構造化ロギングを設定します。

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

    CloudWatchメトリクスはlogMetricsミドルウェアで自動収集されます。カスタムメトリクスを追加可能:

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

    Lambda関数生成時に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型になります。

    ジェネレータは最適化されたLambdaデプロイパッケージのためesbuildを自動設定します:

    特定のLambda関数をバンドル:

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

    プロジェクト内の全Lambda関数をバンドル:

    Terminal window
    pnpm 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');
    }
    }

    これにより以下が設定されます:

    1. AWS Lambda関数
    2. CloudWatchロググループ
    3. X-Rayトレーシング設定
    4. CloudWatchメトリクス名前空間

    この関数はLambdaイベントソースのターゲットとして使用可能です:

    以下はEventBridgeスケジュールでLambda関数を起動する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)],
    });
    }
    }