Funzione Lambda TypeScript
Il generatore di Funzioni Lambda TypeScript permette di aggiungere una funzione lambda a un progetto TypeScript esistente.
Questo generatore crea un nuovo handler lambda TypeScript con la configurazione dell’infrastruttura AWS CDK. L’handler generato utilizza AWS Lambda Powertools for TypeScript per l’osservabilità, inclusi logging, tracciamento AWS X-Ray e metriche CloudWatch, oltre a una validazione opzionale degli eventi tramite Parser di AWS Lambda Powertools.
Utilizzo
Sezione intitolata “Utilizzo”Generare una funzione lambda TypeScript
Sezione intitolata “Generare una funzione lambda TypeScript”Puoi generare una funzione lambda in due modi:
- Installa il Nx Console VSCode Plugin se non l'hai già fatto
- Apri la console Nx in VSCode
- Clicca su
Generate (UI)
nella sezione "Common Nx Commands" - Cerca
@aws/nx-plugin - ts#lambda-function
- Compila i parametri richiesti
- Clicca su
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
Puoi anche eseguire una prova per vedere quali file verrebbero modificati
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
Opzioni
Sezione intitolata “Opzioni”Parametro | Tipo | Predefinito | Descrizione |
---|---|---|---|
project Obbligatorio | string | - | The project to add the lambda function to |
functionName Obbligatorio | 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 |
Output del Generatore
Sezione intitolata “Output del Generatore”Il generatore aggiungerà i seguenti file al tuo progetto:
Directory<project-name>
Directorysrc/
- <lambda-function>.ts Implementazione della funzione
Il generatore creerà anche un costrutto CDK utilizzabile per distribuire la tua funzione, situato nella directory packages/common/constructs/src/app/lambda-functions
.
Se viene fornita l’opzione functionPath
, il generatore aggiungerà l’handler al percorso specificato all’interno della directory sorgente del progetto:
Directory<project-name>
Directorysrc/
Directory<custom-path>/
- <function-name>.ts Implementazione della funzione
Implementazione della Funzione
Sezione intitolata “Implementazione della Funzione”L’implementazione principale della funzione si trova in <function-name>.ts
. Ecco un esempio:
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: implement};
export const handler = middy() .use(captureLambdaHandler(tracer)) .use(injectLambdaContext(logger)) .use(logMetrics(metrics)) .use(parser({ schema: EventBridgeSchema })) .handler(myFunction);
Il generatore configura automaticamente diverse funzionalità:
- Stack middleware Middy per funzionalità avanzate delle Lambda
- Integrazione AWS Lambda Powertools per l’osservabilità
- Raccolta metriche con CloudWatch
- Type-safety tramite middleware parser
- Bundling esbuild per pacchetti di distribuzione ottimizzati
Osservabilità con AWS Lambda Powertools
Sezione intitolata “Osservabilità con AWS Lambda Powertools”Logging
Sezione intitolata “Logging”Il generatore configura il logging strutturato usando AWS Lambda Powertools con iniezione automatica del contesto tramite middleware Middy.
export const handler = middy() .use(injectLambdaContext(logger)) .handler(myFunction);
Tracing
Sezione intitolata “Tracing”Il tracciamento AWS X-Ray viene configurato automaticamente tramite il middleware captureLambdaHandler
. Puoi aggiungere sottosegmenti personalizzati:
const tracer = new Tracer();
export const myFunction = async ( event: z.infer<typeof EventBridgeSchema>,): Promise<void> => { // Crea un nuovo sottosegmento const subsegment = tracer.getSegment()?.addNewSubsegment('custom-operation'); try { // Logica personalizzata qui } catch (error) { subsegment?.addError(error as Error); throw error; } finally { subsegment?.close(); }};
export const handler = middy() .use(captureLambdaHandler(tracer)) .handler(myFunction);
Metriche
Sezione intitolata “Metriche”Le metriche CloudWatch vengono raccolte automaticamente per ogni richiesta tramite il middleware logMetrics
. Puoi aggiungere metriche personalizzate:
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);
Type Safety
Sezione intitolata “Type Safety”Se hai selezionato un eventSource
durante la generazione della funzione lambda, questa viene strumentata con il middleware parser
di AWS Lambda Powertools. Esempio:
export const myFunction = async ( event: z.infer<typeof EventBridgeSchema>,): Promise<void> => { event.detail // <- type-safe con autocompletamento IDE};
export const handler = middy() .use(parser({ schema: EventBridgeSchema })) .handler(myFunction);
Questo fornisce type safety a tempo di compilazione e validazione a runtime per gli eventi Lambda.
Se non vuoi tipizzare l’evento, puoi selezionare Any
per eventSource
, ottenendo un tipo any
per il parametro event.
Bundling
Sezione intitolata “Bundling”Il generatore configura automaticamente esbuild per pacchetti Lambda ottimizzati:
Esegui il bundle di una funzione specifica con:
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>
Esegui il bundle di tutte le funzioni nel progetto con:
pnpm nx run <project-name>:bundle
yarn nx run <project-name>:bundle
npx nx run <project-name>:bundle
bunx nx run <project-name>:bundle
Distribuzione della Funzione
Sezione intitolata “Distribuzione della Funzione”Il generatore crea un costrutto CDK per distribuire la funzione nella cartella common/constructs
. Puoi usarlo in un’applicazione CDK:
import { MyProjectMyFunction } from ':my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { // Aggiungi la funzione allo stack const fn = new MyProjectMyFunction(this, 'MyFunction'); }}
Questo configura:
- Funzione AWS Lambda
- Log group CloudWatch
- Configurazione tracciamento X-Ray
- Namespace metriche CloudWatch
La funzione può essere usata come target per qualsiasi event source lambda:
L’esempio seguente mostra il codice CDK per invocare la funzione lambda su una schedulazione EventBridge:
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) { // Aggiungi la funzione allo stack const fn = new MyProjectMyFunction(this, 'MyFunction');
// Aggiungi la funzione a una regola schedulata EventBridge const eventRule = new Rule(this, 'MyFunctionScheduleRule', { schedule: Schedule.cron({ minute: '15' }), targets: [new LambdaFunction(fn)], }); }}