Skip to content

TypeScript Lambda Function

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

このジェネレーターは、AWS CDK または Terraform インフラストラクチャセットアップを使用して、新しい TypeScript lambda ハンドラーを作成します。生成されたハンドラーは、ログ記録、AWS X-Ray トレーシング、CloudWatch メトリクスを含む可観測性のために AWS Lambda Powertools for TypeScript を使用し、さらに AWS Lambda Powertools の Parser を使用したイベントのオプションの型安全性も提供します。

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

このジェネレーターを実行@aws/nx-plugin:ts#lambda-function

pnpm nx g @aws/nx-plugin:ts#lambda-function
コマンドを組み立てる7

必須

必須

ジェネレーターオプション7 オプション
project必須string

Lambda関数を追加するプロジェクト

name必須string

追加する関数の名前

eventenumデフォルト: Any

Lambda関数に使用するオプションのイベントソーススキーマ

AnyAlbSchemaAPIGatewayProxyEventSchemaAPIGatewayRequestAuthorizerEventSchemaAPIGatewayTokenAuthorizerEventSchemaAPIGatewayProxyEventV2SchemaAPIGatewayProxyWebsocketEventSchemaAPIGatewayRequestAuthorizerEventV2SchemaCloudFormationCustomResourceCreateSchemaCloudFormationCustomResourceUpdateSchemaCloudFormationCustomResourceDeleteSchemaCloudWatchLogsSchemaPreSignupTriggerSchemaPostConfirmationTriggerSchemaCustomMessageTriggerSchemaMigrateUserTriggerSchemaCustomSMSSenderTriggerSchemaCustomEmailSenderTriggerSchemaDefineAuthChallengeTriggerSchemaCreateAuthChallengeTriggerSchemaVerifyAuthChallengeTriggerSchemaPreTokenGenerationTriggerSchemaV1PreTokenGenerationTriggerSchemaV2AndV3DynamoDBStreamSchemaEventBridgeSchemaKafkaMskEventSchemaKafkaSelfManagedEventSchemaKinesisDataStreamSchemaKinesisFirehoseSchemaKinesisDynamoDBStreamSchemaKinesisFirehoseSqsSchemaLambdaFunctionUrlSchemaS3EventNotificationEventBridgeSchemaS3SchemaS3ObjectLambdaEventSchemaS3SqsEventNotificationSchemaSesSchemaSnsSchemaSqsSchemaTransferFamilySchemaVpcLatticeSchemaVpcLatticeV2Schema
infraenumデフォルト: lambda

Lambda関数をデプロイするインフラストラクチャのタイプ

lambdanone
iacenumデフォルト: inherit

優先するIaCプロバイダー。デフォルトでは初期選択から継承されます。

inheritcdkterraform
functionPathstring

関数を追加するプロジェクトソースディレクトリ内のオプションのサブディレクトリ

preferInstallDependenciesbooleanデフォルト: true

ジェネレーター実行後に依存関係のインストールを優先するかどうか。複数のジェネレーターをバッチ処理する際にインストールを延期する場合はfalseに設定します(後続のジェネレーターがNxプロジェクトグラフを計算できるよう、必要に応じてインストールは実行されます)。最後に一度だけインストールします。

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

  • Directory<project-name>
    • Directorysrc/
      • <lambda-function>.ts Function implementation
    • rolldown.config.ts Bundling configuration for the function
    • .gitignore Ignores the temporary configs Rolldown writes

ジェネレーターは、プロジェクトの project.jsonbundle ターゲットを追加し、ハンドラーがインポートする Powertools、Middy、Zod のランタイム依存関係を package.json に追加します。

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

  • Directory<project-name>
    • Directorysrc/
      • Directory<custom-path>/
        • <function-name>.ts Function implementation

このジェネレーターは、選択した iac に基づいてインフラストラクチャをコードとして提供するため、関連する CDK コンストラクトまたは Terraform モジュールを含む packages/common にプロジェクトを作成します。

共通のインフラストラクチャコードプロジェクトは、次のように構成されています:

  • Directorypackages/common/constructs
    • Directorysrc
      • Directoryapp/ プロジェクト/ジェネレーター固有のインフラストラクチャ用のコンストラクト
      • Directorycore/ app 内のコンストラクトによって再利用される汎用コンストラクト
      • index.ts app からコンストラクトをエクスポートするエントリーポイント
    • project.json プロジェクトのビルドターゲットと設定

ジェネレーターは、選択した iac に基づいて関数をデプロイするための Infrastructure as Code を作成します:

ジェネレーターは、関数をデプロイするために使用できる CDK コンストラクトを作成します。これは packages/common/constructs/src/app/lambda-functions ディレクトリに配置されます。

デプロイされた関数は以下のアーキテクチャを持ち、ログ、メトリクス、トレースは CloudWatch と X-Ray に送信されます:

Loading the diagram…

ジェネレーターは関数自体を提供します。イベントソースを呼び出すためにスタック内で接続します(例:API Gateway 統合、EventBridge ルール、S3 通知、または SQS イベントソースマッピング)。

メインの関数実装は <function-name>.ts にあります。以下は例です:

import { parser } from '@aws-lambda-powertools/parser/middleware';
import { EventBridgeSchema } from '@aws-lambda-powertools/parser/schemas';
import { z } from 'zod';
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 type { Context } from 'aws-lambda';
export type { Context };
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: implement
};
export const handler = middy()
.use(captureLambdaHandler(tracer))
.use(injectLambdaContext(logger))
.use(logMetrics(metrics))
.use(parser({ schema: EventBridgeSchema }))
.handler(myFunction);

ジェネレーターは、いくつかの機能を自動的にセットアップします:

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

AWS Lambda Powertools による可観測性

Section titled “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> => {
// Creates a new subsegment
const subsegment = tracer.getSegment()?.addNewSubsegment('custom-operation');
try {
// Your logic here
} 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);
event ≠ Any

lambda 関数を生成する際に event を選択した場合、関数は AWS Lambda Powertools の parser ミドルウェア でインストルメント化されます。例:

export const myFunction = async (
event: z.infer<typeof EventBridgeSchema>,
): Promise<void> => {
event.detail // <- type-safe with IDE autocompletion
};
export const handler = middy()
.use(parser({ schema: EventBridgeSchema }))
.handler(myFunction);

これにより、Lambda イベントのコンパイル時の型安全性とランタイム検証が提供されます。

event = Any

eventAny を選択した場合、parser ミドルウェアは組み込まれず、event パラメータは any として型付けされます。コンパイル時の型安全性とランタイム検証が必要な場合は、特定の event を指定して関数を再生成してください。

ジェネレーターは、Rolldown を使用してデプロイメントパッケージを作成する bundle ターゲットを自動的に設定します:

Terminal window
pnpm nx bundle <project-name>

Rolldown の設定は rolldown.config.ts にあり、生成するバンドルごとにエントリーがあります。Rolldown は、定義されている場合、複数のバンドルを並列で作成することを管理します。

このジェネレーターは、選択した iac に基づいて CDK または Terraform のインフラストラクチャコードを作成します。これを使用して関数をデプロイできます。

このジェネレーターは、common/constructs フォルダに関数をデプロイするための CDK コンストラクトを作成します。これを CDK アプリケーションで使用できます:

import { MyProjectMyFunction } from '@my-scope/common-constructs';
export class ExampleStack extends Stack {
constructor(scope: Construct, id: string) {
// Add the function to your stack
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) {
// Add the function to your stack
const fn = new MyProjectMyFunction(this, 'MyFunction');
// Add the function to an EventBridge scheduled rule
const eventRule = new Rule(this, 'MyFunctionScheduleRule', {
schedule: Schedule.cron({ minute: '15' }),
targets: [new LambdaFunction(fn)],
});
}
}