Salta ai contenuti

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 configurazione infrastrutturale AWS CDK o Terraform. L’handler generato utilizza AWS Lambda Powertools for TypeScript per l’osservabilità, inclusi logging, tracciamento AWS X-Ray e metriche CloudWatch, oltre a un’opzionale type-safety per gli eventi tramite il Parser di AWS Lambda Powertools.

Puoi generare una funzione lambda in due modi:

  1. Installa il Nx Console VSCode Plugin se non l'hai già fatto
  2. Apri la console Nx in VSCode
  3. Clicca su Generate (UI) nella sezione "Common Nx Commands"
  4. Cerca @aws/nx-plugin - ts#lambda-function
  5. Compila i parametri richiesti
    • Clicca su Generate
    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
    iacProvider string Inherit The preferred IaC provider. By default this is inherited from your initial selection.

    Il generatore aggiungerà i seguenti file al tuo progetto:

    • Directory<project-name>
      • Directorysrc/
        • <lambda-function>.ts Implementazione della funzione

    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

    Poiché questo generatore fornisce infrastruttura come codice basata sul tuo iacProvider selezionato, creerà un progetto in packages/common che include i relativi costrutti CDK o moduli Terraform.

    Il progetto comune di infrastruttura come codice è strutturato come segue:

    • Directorypackages/common/constructs
      • Directorysrc
        • Directoryapp/ Construct per l’infrastruttura specifica di un progetto/generatore
        • Directorycore/ Construct generici riutilizzati dai construct in app
        • index.ts Punto di ingresso che esporta i construct da app
      • project.json Target di build e configurazione del progetto

    Il generatore crea infrastruttura as code per distribuire la tua funzione in base al iacProvider selezionato:

    Il generatore crea un costrutto CDK utilizzabile per distribuire la tua funzione, residente nella directory packages/common/constructs/src/app/lambda-functions.

    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à:

    1. Middleware stack Middy per funzionalità Lambda avanzate
    2. Integrazione AWS Lambda Powertools per l’osservabilità
    3. Raccolta metriche con CloudWatch
    4. Type-safety tramite middleware parser
    5. Bundling con Rolldown per pacchetti di distribuzione ottimizzati

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

    Il tracciamento AWS X-Ray è configurato automaticamente tramite il middleware captureLambdaHandler. Puoi aggiungere sottosegmenti personalizzati ai tuoi trace:

    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 qui
    } catch (error) {
    subsegment?.addError(error as Error);
    throw error;
    } finally {
    subsegment?.close();
    }
    };
    export const handler = middy()
    .use(captureLambdaHandler(tracer))
    .handler(myFunction);

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

    Se hai selezionato un eventSource durante la generazione della tua 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 compile-time e validazione runtime per gli eventi Lambda.

    Se non desideri tipizzare l’evento, puoi selezionare Any come eventSource, risultando in un tipo any per il parametro event.

    Il generatore configura automaticamente un target bundle che utilizza Rolldown per creare un pacchetto di distribuzione:

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

    La configurazione di Rolldown si trova in rolldown.config.ts, con un’entry per bundle da generare. Rolldown gestisce la creazione di più bundle in parallelo se definiti.

    Questo generatore crea infrastrutture come codice CDK o Terraform in base al iacProvider selezionato. Puoi utilizzarlo per distribuire la tua funzione.

    Questo generatore crea un costrutto CDK per distribuire la tua funzione nella cartella common/constructs. Puoi utilizzarlo in un’applicazione CDK:

    import { MyProjectMyFunction } from ':my-scope/common-constructs';
    export class ExampleStack extends Stack {
    constructor(scope: Construct, id: string) {
    // Aggiunge la funzione al tuo stack
    const fn = new MyProjectMyFunction(this, 'MyFunction');
    }
    }

    Configura automaticamente:

    1. Funzione AWS Lambda
    2. Gruppo di log CloudWatch
    3. Configurazione del tracciamento X-Ray
    4. Namespace delle metriche CloudWatch

    La funzione può essere utilizzata come target per qualsiasi sorgente eventi Lambda:

    L’esempio seguente mostra il codice CDK per invocare la tua funzione Lambda su una pianificazione usando 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) {
    // Aggiunge la funzione al tuo stack
    const fn = new MyProjectMyFunction(this, 'MyFunction');
    // Aggiunge la funzione a una regola pianificata di EventBridge
    const eventRule = new Rule(this, 'MyFunctionScheduleRule', {
    schedule: Schedule.cron({ minute: '15' }),
    targets: [new LambdaFunction(fn)],
    });
    }
    }