Funzione Lambda TypeScript
Il generatore di funzioni Lambda TypeScript fornisce la possibilità di aggiungere una funzione lambda a un progetto TypeScript esistente.
Questo generatore crea un nuovo handler lambda TypeScript con configurazione dell’infrastruttura AWS CDK o Terraform. L’handler generato utilizza AWS Lambda Powertools for TypeScript per l’osservabilità, inclusi logging, tracciamento AWS X-Ray e CloudWatch Metrics, oltre alla sicurezza dei tipi opzionale per l’evento utilizzando il Parser from AWS Lambda Powertools
Utilizzo
Sezione intitolata “Utilizzo”Genera una funzione lambda TypeScript
Sezione intitolata “Genera una funzione lambda TypeScript”Puoi generare una funzione lambda in due modi:
pnpm nx g @aws/nx-plugin:ts#lambda-functionyarn nx g @aws/nx-plugin:ts#lambda-functionnpx nx g @aws/nx-plugin:ts#lambda-functionbunx nx g @aws/nx-plugin:ts#lambda-functionPuoi anche eseguire una prova per vedere quali file verrebbero modificati
pnpm nx g @aws/nx-plugin:ts#lambda-function --dry-runyarn nx g @aws/nx-plugin:ts#lambda-function --dry-runnpx nx g @aws/nx-plugin:ts#lambda-function --dry-runbunx nx g @aws/nx-plugin:ts#lambda-function --dry-run- 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
Opzioni
Sezione intitolata “Opzioni”| Parametro | Tipo | Predefinito | Descrizione |
|---|---|---|---|
| project Obbligatorio | string | - | Il progetto a cui aggiungere la funzione lambda |
| name Obbligatorio | string | - | Il nome della funzione da aggiungere |
| functionPath | string | - | Sottodirectory opzionale all'interno della directory sorgente del progetto in cui aggiungere la funzione |
| event | Any | AlbSchema | APIGatewayProxyEventSchema | APIGatewayRequestAuthorizerEventSchema | APIGatewayTokenAuthorizerEventSchema | APIGatewayProxyEventV2Schema | APIGatewayProxyWebsocketEventSchema | APIGatewayRequestAuthorizerEventV2Schema | CloudFormationCustomResourceCreateSchema | CloudFormationCustomResourceUpdateSchema | CloudFormationCustomResourceDeleteSchema | CloudWatchLogsSchema | PreSignupTriggerSchema | PostConfirmationTriggerSchema | CustomMessageTriggerSchema | MigrateUserTriggerSchema | CustomSMSSenderTriggerSchema | CustomEmailSenderTriggerSchema | DefineAuthChallengeTriggerSchema | CreateAuthChallengeTriggerSchema | VerifyAuthChallengeTriggerSchema | PreTokenGenerationTriggerSchemaV1 | PreTokenGenerationTriggerSchemaV2AndV3 | DynamoDBStreamSchema | EventBridgeSchema | KafkaMskEventSchema | KafkaSelfManagedEventSchema | KinesisDataStreamSchema | KinesisFirehoseSchema | KinesisDynamoDBStreamSchema | KinesisFirehoseSqsSchema | LambdaFunctionUrlSchema | S3EventNotificationEventBridgeSchema | S3Schema | S3ObjectLambdaEventSchema | S3SqsEventNotificationSchema | SesSchema | SnsSchema | SqsSchema | TransferFamilySchema | VpcLatticeSchema | VpcLatticeV2Schema | Any | Schema opzionale della sorgente evento da utilizzare per la funzione lambda |
| infra | lambda | none | lambda | Il tipo di infrastruttura con cui distribuire la tua funzione Lambda. |
| iac | inherit | cdk | terraform | inherit | Il provider IaC preferito. Per impostazione predefinita viene ereditato dalla selezione iniziale. |
| preferInstallDependencies | boolean | true | Se preferire l'installazione delle dipendenze dopo l'esecuzione del generatore. Impostare su false per rimandare l'installazione quando si eseguono più generatori in batch (l'installazione viene comunque eseguita se necessaria affinché i generatori successivi possano calcolare il grafo dei progetti Nx); installare una volta alla fine. |
Output del generatore
Sezione intitolata “Output del generatore”Il generatore aggiungerà i seguenti file al tuo progetto:
Directory<project-name>
Directorysrc/
- <lambda-function>.ts Function implementation
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 Function implementation
Infrastruttura
Sezione intitolata “Infrastruttura”Poiché questo generatore fornisce infrastruttura come codice basata sul tuo iac scelto, creerà un progetto in packages/common che include i costrutti CDK o i moduli Terraform pertinenti.
Il progetto comune di infrastruttura come codice è strutturato come segue:
Directorypackages/common/constructs
Directorysrc
Directoryapp/ Constructs for infrastructure specific to a project/generator
- …
Directorycore/ Generic constructs which are reused by constructs in
app- …
- index.ts Entry point exporting constructs from
app
- project.json Project build targets and configuration
Directorypackages/common/terraform
Directorysrc
Directoryapp/ Terraform modules for infrastructure specific to a project/generator
- …
Directorycore/ Generic modules which are reused by modules in
app- …
- project.json Project build targets and configuration
Il generatore crea l’infrastruttura come codice per distribuire la tua funzione in base al tuo iac selezionato:
Il generatore crea un costrutto CDK che può essere utilizzato per distribuire la tua funzione, che risiede nella directory packages/common/constructs/src/app/lambda-functions.
Il generatore crea un modulo Terraform che può essere utilizzato per distribuire la tua funzione, che risiede nella directory packages/common/terraform/src/app/lambda-functions/<function-name>.
Architettura
Sezione intitolata “Architettura”La funzione distribuita ha la seguente architettura:
Il generatore fornisce la funzione stessa; è necessario collegare la sorgente degli eventi nello stack per invocarla (ad esempio, un’integrazione API Gateway, una regola EventBridge, una notifica S3 o un mapping di sorgente eventi SQS).
Implementazione della tua funzione
Sezione intitolata “Implementazione della tua 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 di middleware Middy per funzionalità Lambda avanzate
- Integrazione AWS Lambda Powertools per l’osservabilità
- Raccolta di metriche con CloudWatch
- Sicurezza dei tipi utilizzando il middleware parser
- Bundling con Rolldown 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 utilizzando AWS Lambda Powertools con iniezione automatica del contesto tramite middleware Middy.
export const handler = middy() .use(injectLambdaContext(logger)) .handler(myFunction);Tracciamento
Sezione intitolata “Tracciamento”Il tracciamento AWS X-Ray è configurato automaticamente tramite il middleware captureLambdaHandler. Puoi aggiungere sottosegmenti personalizzati alle tue tracce:
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);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);Sicurezza dei tipi
Sezione intitolata “Sicurezza dei tipi”Se hai scelto un event durante la generazione della tua funzione lambda, la tua funzione è strumentata con il parser middleware from AWS Lambda Powertools. Ad esempio:
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);Questo fornisce sicurezza dei tipi in fase di compilazione e validazione in fase di esecuzione per i tuoi eventi Lambda.
Se hai selezionato Any per il tuo event, il middleware parser non è collegato e il parametro event è tipizzato come any. Rigenera la funzione con un event specifico se desideri la sicurezza dei tipi in fase di compilazione e la validazione in fase di esecuzione.
Bundling
Sezione intitolata “Bundling”Il generatore configura automaticamente un target bundle che utilizza Rolldown per creare un pacchetto di distribuzione:
pnpm nx bundle <project-name>yarn nx bundle <project-name>npx nx bundle <project-name>bunx nx bundle <project-name>La configurazione di Rolldown si trova in rolldown.config.ts, con una voce per ogni bundle da generare. Rolldown gestisce la creazione di più bundle in parallelo se definiti.
Distribuzione della tua funzione
Sezione intitolata “Distribuzione della tua funzione”Questo generatore crea infrastruttura come codice CDK o Terraform in base al tuo iac 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) { // Add the function to your stack const fn = new MyProjectMyFunction(this, 'MyFunction'); }}Questo configura:
- Funzione AWS Lambda
- Gruppo di log CloudWatch
- Configurazione del tracciamento X-Ray
- Namespace delle metriche CloudWatch
Questa funzione può quindi essere utilizzata come destinazione per qualsiasi sorgente di eventi lambda:
L’esempio seguente dimostra il codice CDK per invocare la tua funzione lambda secondo una pianificazione utilizzando 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) { // 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)], }); }}Questo generatore crea un modulo Terraform per distribuire la tua funzione nella cartella common/terraform. Istanzia il modulo condiviso core/asset-bucket una volta per distribuzione e passa il suo bucket_name nell’input asset_bucket_name:
module "asset_bucket" { source = "../../common/terraform/src/core/asset-bucket"}
module "my_project_my_function" { source = "../../common/terraform/src/app/lambda-functions/my-project-my-function"
asset_bucket_name = module.asset_bucket.bucket_name
env = { SOME_VARIABLE = "some value" }
additional_iam_policy_statements = [ # Add any additional permissions your function needs ]}Questo configura:
- Funzione AWS Lambda
- Gruppo di log CloudWatch
- Configurazione del tracciamento X-Ray
- Namespace delle metriche CloudWatch
Questa funzione può quindi essere utilizzata come destinazione per qualsiasi sorgente di eventi lambda. L’esempio seguente dimostra il codice Terraform per invocare la tua funzione lambda secondo una pianificazione utilizzando EventBridge:
# EventBridge rule for scheduled executionresource "aws_cloudwatch_event_rule" "my_function_schedule" { name = "my-function-schedule" description = "Trigger my function every 15 minutes" schedule_expression = "cron(15 * * * ? *)"}
# EventBridge targetresource "aws_cloudwatch_event_target" "lambda_target" { rule = aws_cloudwatch_event_rule.my_function_schedule.name target_id = "MyFunctionTarget" arn = module.my_project_my_function.function_arn}
# Permission for EventBridge to invoke the Lambda functionresource "aws_lambda_permission" "allow_eventbridge" { statement_id = "AllowExecutionFromEventBridge" action = "lambda:InvokeFunction" function_name = module.my_project_my_function.function_name principal = "events.amazonaws.com" source_arn = aws_cloudwatch_event_rule.my_function_schedule.arn}