Richiama una funzione Lambda da un trigger di Amazon DocumentDB - AWS Lambda

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

Richiama una funzione Lambda da un trigger di Amazon DocumentDB

I seguenti esempi di codice mostrano come implementare una funzione Lambda che riceve un evento attivato dalla ricezione di record da un flusso di modifiche di DocumentDB. La funzione recupera il payload DocumentDB e registra il contenuto del record.

Go
SDK per Go V2
Nota

C'è altro su. GitHub Trova l'esempio completo e scopri come eseguire la configurazione e l'esecuzione nel repository di Esempi serverless.

Consumo di un evento Amazon DocumentDB con Lambda utilizzando Go.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package main import ( "context" "encoding/json" "fmt" "github.com/aws/aws-lambda-go/lambda" ) type Event struct { Events []Record `json:"events"` } type Record struct { Event struct { OperationType string `json:"operationType"` NS struct { DB string `json:"db"` Coll string `json:"coll"` } `json:"ns"` FullDocument interface{} `json:"fullDocument"` } `json:"event"` } func main() { lambda.Start(handler) } func handler(ctx context.Context, event Event) (string, error) { fmt.Println("Loading function") for _, record := range event.Events { logDocumentDBEvent(record) } return "OK", nil } func logDocumentDBEvent(record Record) { fmt.Printf("Operation type: %s\n", record.Event.OperationType) fmt.Printf("db: %s\n", record.Event.NS.DB) fmt.Printf("collection: %s\n", record.Event.NS.Coll) docBytes, _ := json.MarshalIndent(record.Event.FullDocument, "", " ") fmt.Printf("Full document: %s\n", string(docBytes)) }
JavaScript
SDK per (v3 JavaScript )
Nota

C'è altro da fare. GitHub Trova l'esempio completo e scopri come eseguire la configurazione e l'esecuzione nel repository di Esempi serverless.

Consumo di un evento Amazon DocumentDB con Lambda utilizzando. JavaScript

console.log('Loading function'); exports.handler = async (event, context) => { event.events.forEach(record => { logDocumentDBEvent(record); }); return 'OK'; }; const logDocumentDBEvent = (record) => { console.log('Operation type: ' + record.event.operationType); console.log('db: ' + record.event.ns.db); console.log('collection: ' + record.event.ns.coll); console.log('Full document:', JSON.stringify(record.event.fullDocument, null, 2)); };

Consumo di un evento Amazon DocumentDB con Lambda utilizzando TypeScript

import { DocumentDBEventRecord, DocumentDBEventSubscriptionContext } from 'aws-lambda'; console.log('Loading function'); export const handler = async ( event: DocumentDBEventSubscriptionContext, context: any ): Promise<string> => { event.events.forEach((record: DocumentDBEventRecord) => { logDocumentDBEvent(record); }); return 'OK'; }; const logDocumentDBEvent = (record: DocumentDBEventRecord): void => { console.log('Operation type: ' + record.event.operationType); console.log('db: ' + record.event.ns.db); console.log('collection: ' + record.event.ns.coll); console.log('Full document:', JSON.stringify(record.event.fullDocument, null, 2)); };
PHP
SDK per PHP
Nota

C'è altro da fare. GitHub Trova l'esempio completo e scopri come eseguire la configurazione e l'esecuzione nel repository di Esempi serverless.

Consumo di un evento Amazon DocumentDB con Lambda utilizzando PHP.

<?php require __DIR__.'/vendor/autoload.php'; use Bref\Context\Context; use Bref\Event\Handler; class DocumentDBEventHandler implements Handler { public function handle($event, Context $context): string { $events = $event['events'] ?? []; foreach ($events as $record) { $this->logDocumentDBEvent($record['event']); } return 'OK'; } private function logDocumentDBEvent($event): void { // Extract information from the event record $operationType = $event['operationType'] ?? 'Unknown'; $db = $event['ns']['db'] ?? 'Unknown'; $collection = $event['ns']['coll'] ?? 'Unknown'; $fullDocument = $event['fullDocument'] ?? []; // Log the event details echo "Operation type: $operationType\n"; echo "Database: $db\n"; echo "Collection: $collection\n"; echo "Full document: " . json_encode($fullDocument, JSON_PRETTY_PRINT) . "\n"; } } return new DocumentDBEventHandler();
Python
SDK per Python (Boto3)
Nota

C'è di più su. GitHub Trova l'esempio completo e scopri come eseguire la configurazione e l'esecuzione nel repository di Esempi serverless.

Consumo di un evento Amazon DocumentDB con Lambda utilizzando Python.

import json def lambda_handler(event, context): for record in event.get('events', []): log_document_db_event(record) return 'OK' def log_document_db_event(record): event_data = record.get('event', {}) operation_type = event_data.get('operationType', 'Unknown') db = event_data.get('ns', {}).get('db', 'Unknown') collection = event_data.get('ns', {}).get('coll', 'Unknown') full_document = event_data.get('fullDocument', {}) print(f"Operation type: {operation_type}") print(f"db: {db}") print(f"collection: {collection}") print("Full document:", json.dumps(full_document, indent=2))
Ruby
SDK per Ruby
Nota

C'è di più su. GitHub Trova l'esempio completo e scopri come eseguire la configurazione e l'esecuzione nel repository di Esempi serverless.

Consumo di un evento Amazon DocumentDB con Lambda utilizzando Ruby.

require 'json' def lambda_handler(event:, context:) event['events'].each do |record| log_document_db_event(record) end 'OK' end def log_document_db_event(record) event_data = record['event'] || {} operation_type = event_data['operationType'] || 'Unknown' db = event_data.dig('ns', 'db') || 'Unknown' collection = event_data.dig('ns', 'coll') || 'Unknown' full_document = event_data['fullDocument'] || {} puts "Operation type: #{operation_type}" puts "db: #{db}" puts "collection: #{collection}" puts "Full document: #{JSON.pretty_generate(full_document)}" end
Rust
SDK per Rust
Nota

C'è di più su. GitHub Trova l'esempio completo e scopri come eseguire la configurazione e l'esecuzione nel repository di Esempi serverless.

Consumo di un evento Amazon DocumentDB con Lambda utilizzando Rust.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use lambda_runtime::{service_fn, tracing, Error, LambdaEvent}; use aws_lambda_events::{ event::documentdb::{DocumentDbEvent, DocumentDbInnerEvent}, }; // Built with the following dependencies: //lambda_runtime = "0.11.1" //serde_json = "1.0" //tokio = { version = "1", features = ["macros"] } //tracing = { version = "0.1", features = ["log"] } //tracing-subscriber = { version = "0.3", default-features = false, features = ["fmt"] } //aws_lambda_events = "0.15.0" async fn function_handler(event: LambdaEvent<DocumentDbEvent>) ->Result<(), Error> { tracing::info!("Event Source ARN: {:?}", event.payload.event_source_arn); tracing::info!("Event Source: {:?}", event.payload.event_source); let records = &event.payload.events; if records.is_empty() { tracing::info!("No records found. Exiting."); return Ok(()); } for record in records{ log_document_db_event(record); } tracing::info!("Document db records processed"); // Prepare the response Ok(()) } fn log_document_db_event(record: &DocumentDbInnerEvent)-> Result<(), Error>{ tracing::info!("Change Event: {:?}", record.event); Ok(()) } #[tokio::main] async fn main() -> Result<(), Error> { tracing_subscriber::fmt() .with_max_level(tracing::Level::INFO) .with_target(false) .without_time() .init(); let func = service_fn(function_handler); lambda_runtime::run(func).await?; Ok(()) }

Per un elenco completo delle guide per sviluppatori AWS SDK e degli esempi di codice, consulta. Usare Lambda con un SDK AWS Questo argomento include anche informazioni su come iniziare e dettagli sulle versioni precedenti dell'SDK.