TypeScriptのLambda関数
TypeScript Lambda Function ジェネレータは、既存のTypeScriptプロジェクトにLambda関数を追加する機能を提供します。
このジェネレータはAWS CDKインフラストラクチャ設定を含む新しいTypeScript Lambdaハンドラを作成します。生成されたハンドラは、AWS Lambda Powertools for TypeScriptを使用して、ロギング、AWS X-Rayトレーシング、CloudWatchメトリクスなどの観測可能性を実現し、AWS Lambda PowertoolsのParserを使用したイベントの型安全性(オプション)を提供します。
TypeScript Lambda関数の生成
Section titled “TypeScript Lambda関数の生成”Lambda関数は2つの方法で生成できます:
- インストール 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 |
ジェネレータの出力
Section titled “ジェネレータの出力”ジェネレータはプロジェクトに以下のファイルを追加します:
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);
ジェネレータは以下の機能を自動的に設定します:
- 拡張Lambda機能のためのMiddyミドルウェアスタック
- 観測可能性のためのAWS Lambda Powertools統合
- CloudWatchを使ったメトリクス収集
- パーサーミドルウェアを使用した型安全性
- 最適化されたデプロイパッケージのためのesbuildバンドリング
AWS Lambda Powertoolsによる観測可能性
Section titled “AWS Lambda Powertoolsによる観測可能性”ジェネレータはMiddyミドルウェアを使用した自動コンテキスト注入で、構造化ロギングを設定します。
export const handler = middy() .use(injectLambdaContext(logger)) .handler(myFunction);
トレーシング
Section titled “トレーシング”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);
これにより、コンパイル時の型安全性とランタイムバリデーションが実現されます。
イベントの型指定が必要ない場合は、eventSource
にAny
を選択できます。これによりイベントパラメータはany
型になります。
バンドリング
Section titled “バンドリング”ジェネレータは最適化されたLambdaデプロイパッケージのためesbuildを自動設定します:
特定のLambda関数をバンドル:
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>
プロジェクト内の全Lambda関数をバンドル:
pnpm nx run <project-name>:bundle
yarn nx run <project-name>:bundle
npx nx run <project-name>:bundle
bunx nx run <project-name>:bundle
関数のデプロイ
Section titled “関数のデプロイ”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メトリクス名前空間
この関数は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)], }); }}