diff --git a/docs/contributing/conventions.md b/docs/contributing/conventions.md index 94291708c6..a8ee3bcc01 100644 --- a/docs/contributing/conventions.md +++ b/docs/contributing/conventions.md @@ -36,7 +36,7 @@ There are also a few other workspaces that are not utilities published to npm, b * `examples/snippets`: contains the documentation code snippets * `examples/app`: contains an example project that can be deployed via AWS CDK or AWS SAM -* `layers`: contains the code used to build and publish the [Lambda layers](../index.md#lambda-layer) +* `layers`: contains the code used to build and publish the [Lambda layers](../getting-started/lambda-layers.md) ## Testing definition diff --git a/docs/environment-variables.md b/docs/environment-variables.md new file mode 100644 index 0000000000..66bf5fb52a --- /dev/null +++ b/docs/environment-variables.md @@ -0,0 +1,43 @@ +--- +title: Environment Variables +description: Environment Variables for Powertools for AWS Lambda +--- + + + +You can configure Powertools for AWS Lambda using environment variables. This is useful when you want to set configuration values in your Infrastructure as Code (IaC) templates or when you want to override default values without changing your code. + +???+ info + Explicit parameters in your code take precedence over environment variables + +| Environment variable | Description | Utility | Default | +| -------------------------------------------- |------------------------------------------------------------------------------------------| -------------------------------------- |------------------------------------------------| +| **POWERTOOLS_SERVICE_NAME** | Set service name used for tracing namespace, metrics dimension and structured logging | All | `service_undefined` | +| **POWERTOOLS_METRICS_NAMESPACE** | Set namespace used for metrics | [Metrics](features/metrics.md) | `default_namespace` | +| **POWERTOOLS_METRICS_FUNCTION_NAME** | Function name used as dimension for the `ColdStart` metric | [Metrics](features/metrics.md) | [See docs](features/metrics.md#setting-function-name) | +| **POWERTOOLS_METRICS_ENABLED** | Explicitly disables emitting metrics to stdout | [Metrics](features/metrics.md) | `true` | +| **POWERTOOLS_TRACE_ENABLED** | Explicitly disables tracing | [Tracer](features/tracer.md) | `true` | +| **POWERTOOLS_TRACER_CAPTURE_RESPONSE** | Capture Lambda or method return as metadata. | [Tracer](features/tracer.md) | `true` | +| **POWERTOOLS_TRACER_CAPTURE_ERROR** | Capture Lambda or method exception as metadata. | [Tracer](features/tracer.md) | `true` | +| **POWERTOOLS_TRACER_CAPTURE_HTTPS_REQUESTS** | Capture HTTP(s) requests as segments. | [Tracer](features/tracer.md) | `true` | +| **POWERTOOLS_LOGGER_LOG_EVENT** | Log incoming event | [Logger](features/logger.md) | `false` | +| **POWERTOOLS_LOGGER_SAMPLE_RATE** | Debug log sampling | [Logger](features/logger.md) | `0` | +| **POWERTOOLS_DEV** | Pretty-print logs, disable metrics flushing, and disable traces - use for dev only | See section below | `false` | +| **POWERTOOLS_LOG_LEVEL** | Sets how verbose Logger should be, from the most verbose to the least verbose (no logs) | [Logger](features/logger.md) | `INFO` | +| **POWERTOOLS_PARAMETERS_MAX_AGE** | Adjust how long values are kept in cache (in seconds) | [Parameters](features/parameters.md) | `5` | +| **POWERTOOLS_PARAMETERS_SSM_DECRYPT** | Set whether to decrypt or not values retrieved from AWS Systems Manager Parameters Store | [Parameters](features/parameters.md) | `false` | +| **POWERTOOLS_IDEMPOTENCY_DISABLED** | Disable the Idempotency logic without changing your code, useful for testing | [Idempotency](features/idempotency.md) | `false` | + +Each Utility page provides information on example values and allowed values. + +## Dev Mode + +Whether you're prototyping locally or against a non-production environment, you can use `POWERTOOLS_DEV` to increase verbosity across multiple utilities. + +When `POWERTOOLS_DEV` is set to a truthy value (`1`, `true`), it'll have the following effects: + +| Utility | Effect | +| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Logger** | Increase JSON indentation to 4 and uses global `console` to emit logs to ease testing and local debugging when running functions locally. However, Amazon CloudWatch Logs view will degrade as each new line is treated as a new message | +| **Tracer** | Disables tracing operations in non-Lambda environments. This already happens automatically in the Tracer utility | +| **Metrics** | Disables emitting metrics to stdout. Can be overridden by setting `POWERTOOLS_METRICS_ENABLED` to `true` | diff --git a/docs/utilities/batch.md b/docs/features/batch.md similarity index 100% rename from docs/utilities/batch.md rename to docs/features/batch.md diff --git a/docs/core/event-handler/api-gateway.md b/docs/features/event-handler/api-gateway.md similarity index 95% rename from docs/core/event-handler/api-gateway.md rename to docs/features/event-handler/api-gateway.md index c714ec550c..adf097f13b 100644 --- a/docs/core/event-handler/api-gateway.md +++ b/docs/features/event-handler/api-gateway.md @@ -13,7 +13,7 @@ Event handler for Amazon API Gateway REST and HTTP APIs, Application Loader Bala * Lightweight routing to reduce boilerplate for API Gateway REST/HTTP API, ALB and Lambda Function URLs. * Support for CORS, binary and Gzip compression, Decimals JSON encoding and bring your own JSON serializer -* Built-in integration with [Parser](../../utilities/parser.md){target="_blank"} for easy payload validation and parsing +* Built-in integration with [Parser](../../features/parser.md){target="_blank"} for easy payload validation and parsing * Works with micro function (one or a few routes) and monolithic functions (all routes) ## Getting started diff --git a/docs/utilities/idempotency.md b/docs/features/idempotency.md similarity index 97% rename from docs/utilities/idempotency.md rename to docs/features/idempotency.md index fde149ebbb..be4addef79 100644 --- a/docs/utilities/idempotency.md +++ b/docs/features/idempotency.md @@ -162,13 +162,6 @@ The function this example has two arguments, note that while wrapping it with th You can also use the `@idempotent` decorator to make your Lambda handler idempotent, similar to the `makeIdempotent` function wrapper. -!!! info - The class method decorators in this project follow the experimental implementation enabled via the [`experimentalDecorators` compiler option](https://www.typescriptlang.org/tsconfig#experimentalDecorators) in TypeScript. - - Additionally, they are implemented to decorate async methods. When decorating a synchronous one, the decorator replaces its implementation with an async one causing the caller to have to `await` the now decorated method. - - If this is not the desired behavior, you can use one of the other patterns to make your logic idempotent. - === "index.ts" ```typescript hl_lines="17" @@ -181,15 +174,8 @@ You can also use the `@idempotent` decorator to make your Lambda handler idempot --8<-- "examples/snippets/idempotency/types.ts" ``` -You can use the decorator on your Lambda handler or on any function that returns a response to make it idempotent. This is useful when you want to make a specific logic idempotent, for example when your Lambda handler performs multiple side effects and you only want to make a specific one idempotent. -The configuration options for the `@idempotent` decorator are the same as the ones for the `makeIdempotent` function wrapper. - ### MakeHandlerIdempotent Middy middleware -!!! tip "A note about Middy" - We guarantee support for Middy.js `v4.x` through `v6.x` versions. - Check their docs to learn more about [Middy and its middleware stack](https://middy.js.org/docs/intro/getting-started){target="_blank"} as well as [best practices when working with Powertools](https://middy.js.org/docs/integrations/lambda-powertools#best-practices){target="_blank"}. - If you are using [Middy.js](https://middy.js.org){target="_blank"} as your middleware engine, you can use the `makeHandlerIdempotent` middleware to make your Lambda handler idempotent. Similar to the `makeIdempotent` function wrapper, you can quickly make your Lambda handler idempotent by initializing the `DynamoDBPersistenceLayer` class and using it with the `makeHandlerIdempotent` middleware. diff --git a/docs/features/index.md b/docs/features/index.md new file mode 100644 index 0000000000..808248f9a6 --- /dev/null +++ b/docs/features/index.md @@ -0,0 +1,82 @@ +--- +title: Features +description: Features of Powertools for AWS Lambda +--- + + + +
+ +- __Tracer__ + + --- + + Instrument your code with minimal effort. Capture traces and metadata to understand the performance of your Lambda functions. + + [:octicons-arrow-right-24: Read more](./tracer.md) + +- __Logger__ + + --- + + JSON Structured logging made easier, key management, buffering, and Middy.js middleware to enrich structured logging with key Lambda context details. + + [:octicons-arrow-right-24: Read more](./logger.md) + +- __Metrics__ + + --- + + Custom Metrics created asynchronously via CloudWatch Embedded Metric Format (EMF) + + [:octicons-arrow-right-24: Read more](./metrics.md) + +- __Parameters__ + + --- + + High-level functions to retrieve one or more parameters from AWS SSM Parameter Store, AWS Secrets Manager, AWS AppConfig, and Amazon DynamoDB + + [:octicons-arrow-right-24: Read more](./parameters.md) + +- __Idempotency__ + + --- + + Class method decorator, Middy middleware, and function wrapper to make your Lambda functions idempotent and prevent duplicate execution based on payload content. + + [:octicons-arrow-right-24: Read more](./idempotency.md) + +- __Batch Processing__ + + --- + + Simplify the processing of batches of events with built-in support for SQS and DynamoDB Streams. + + [:octicons-arrow-right-24: Read more](./batch.md) + +- __JMESPath Functions__ + + --- + + Built-in JMESPath functions to easily deserialize common encoded JSON payloads in Lambda functions. + + [:octicons-arrow-right-24: Read more](./jmespath.md) + +- __Parser__ + + --- + + Utility to parse and validate AWS Lambda event payloads using Zod, a TypeScript-first schema declaration and validation library. + + [:octicons-arrow-right-24: Read more](./parser.md) + +- __Validation__ + + --- + + JSON Schema validation for events and responses, including JMESPath support to unwrap events before validation. + + [:octicons-arrow-right-24: Read more](./validation.md) + +
diff --git a/docs/utilities/jmespath.md b/docs/features/jmespath.md similarity index 100% rename from docs/utilities/jmespath.md rename to docs/features/jmespath.md diff --git a/docs/core/logger.md b/docs/features/logger.md similarity index 97% rename from docs/core/logger.md rename to docs/features/logger.md index 6a72664bb3..8fc6bd943c 100644 --- a/docs/core/logger.md +++ b/docs/features/logger.md @@ -56,7 +56,8 @@ These settings will be used across all logs emitted: ???+ info When `POWERTOOLS_DEV` environment variable is present and set to `"true"` or `"1"`, Logger will pretty-print log messages for easier readability. We recommend to use this setting only when debugging on local environments. -See all environment variables in the [Environment variables](../index.md/#environment-variables) section. +See all environment variables in the [Environment variables](../environment-variables.md) section. + Check API docs to learn more about [Logger constructor options](https://docs.powertools.aws.dev/lambda/typescript/latest/api/types/_aws_lambda_powertools_logger.types.ConstructorOptions.html){target="_blank"}. #### Example using AWS Serverless Application Model (SAM) @@ -114,23 +115,12 @@ This functionality will include the following keys in your structured logs: === "Middy Middleware" - !!! tip "A note about Middy" - We guarantee support for Middy.js `v4.x` through `v6.x` versions. - Check their docs to learn more about [Middy and its middleware stack](https://middy.js.org/docs/intro/getting-started){target="_blank"} as well as [best practices when working with Powertools](https://middy.js.org/docs/integrations/lambda-powertools#best-practices){target="_blank"}. - ```typescript hl_lines="2 14" --8<-- "examples/snippets/logger/middy.ts" ``` === "Decorator" - !!! note - The class method decorators in this project follow the experimental implementation enabled via the [`experimentalDecorators` compiler option](https://www.typescriptlang.org/tsconfig#experimentalDecorators) in TypeScript. - - Additionally, they are implemented to decorate async methods. When decorating a synchronous one, the decorator replaces its implementation with an async one causing the caller to have to `await` the now decorated method. - - If this is not the desired behavior, you can call the `logger.injectLambdaContext()` method directly in your handler. - ```typescript hl_lines="8" --8<-- "examples/snippets/logger/decorator.ts" ``` diff --git a/docs/core/metrics.md b/docs/features/metrics.md similarity index 95% rename from docs/core/metrics.md rename to docs/features/metrics.md index f2d61eabf9..0954a7ec0e 100644 --- a/docs/core/metrics.md +++ b/docs/features/metrics.md @@ -201,10 +201,6 @@ You can add default dimensions to your metrics by passing them as parameters in === "Middy middleware" - !!! tip "A note about Middy" - We guarantee support for Middy.js `v4.x` through `v6.x` versions. - Check their docs to learn more about [Middy and its middleware stack](https://middy.js.org/docs/intro/getting-started){target="_blank"} as well as [best practices when working with Powertools](https://middy.js.org/docs/integrations/lambda-powertools#best-practices){target="_blank"}. - ```typescript hl_lines="24-26" --8<-- "examples/snippets/metrics/defaultDimensionsMiddy.ts" ``` @@ -217,13 +213,6 @@ You can add default dimensions to your metrics by passing them as parameters in === "with logMetrics decorator" - !!! note - The class method decorators in this project follow the experimental implementation enabled via the [`experimentalDecorators` compiler option](https://www.typescriptlang.org/tsconfig#experimentalDecorators) in TypeScript. - - Additionally, they are implemented to decorate async methods. When decorating a synchronous one, the decorator replaces its implementation with an async one causing the caller to have to `await` the now decorated method. - - If this is not the desired behavior, you can use the `logMetrics` middleware instead. - ```typescript hl_lines="12" --8<-- "examples/snippets/metrics/defaultDimensionsDecorator.ts" ``` diff --git a/docs/utilities/parameters.md b/docs/features/parameters.md similarity index 99% rename from docs/utilities/parameters.md rename to docs/features/parameters.md index 172be99ae4..bcf72abab4 100644 --- a/docs/utilities/parameters.md +++ b/docs/features/parameters.md @@ -413,7 +413,7 @@ You can use the `awsSdkV3Client` parameter via any of the available [Provider Cl | [DynamoDBProvider](#dynamodbprovider) | `new DynamoDBClient();` | ???+ question "When is this useful?" - Injecting a custom AWS SDK v3 client allows you to [apply tracing](../core/tracer.md#patching-aws-sdk-clients) or make unit/snapshot testing easier, including SDK customizations. + Injecting a custom AWS SDK v3 client allows you to [apply tracing](../features/tracer.md#patching-aws-sdk-clients) or make unit/snapshot testing easier, including SDK customizations. === "SSMProvider" ```typescript hl_lines="5 7" diff --git a/docs/utilities/parser.md b/docs/features/parser.md similarity index 100% rename from docs/utilities/parser.md rename to docs/features/parser.md diff --git a/docs/core/tracer.md b/docs/features/tracer.md similarity index 95% rename from docs/core/tracer.md rename to docs/features/tracer.md index 8ea03d6768..b30e1080b1 100644 --- a/docs/core/tracer.md +++ b/docs/features/tracer.md @@ -153,21 +153,12 @@ You can quickly start by importing the `Tracer` class, initialize it outside the === "Middy Middleware" - !!! tip "A note about Middy" - We guarantee support for Middy.js `v4.x` through `v6.x` versions. - Check their docs to learn more about [Middy and its middleware stack](https://middy.js.org/docs/intro/getting-started){target="_blank"} as well as [best practices when working with Powertools](https://middy.js.org/docs/integrations/lambda-powertools#best-practices){target="_blank"}. - ```typescript hl_lines="2 15 17" --8<-- "examples/snippets/tracer/middy.ts" ``` === "Decorator" - !!! note - The class method decorators in this project follow the experimental implementation enabled via the [`experimentalDecorators` compiler option](https://www.typescriptlang.org/tsconfig#experimentalDecorators) in TypeScript. - - Additionally, they are implemented to decorate async methods. When decorating a synchronous one, the decorator replaces its implementation with an async one causing the caller to have to `await` the now decorated method. - ```typescript hl_lines="8" --8<-- "examples/snippets/tracer/decorator.ts" ``` @@ -185,7 +176,7 @@ When using the `captureLambdaHandler` decorator or middleware, Tracer performs t * Handles the lifecycle of the subsegment * Creates a `ColdStart` annotation to easily filter traces that have had an initialization overhead * Creates a `Service` annotation to easily filter traces that have a specific service name -* Captures any response, or full exceptions generated by the handler, and include them as tracing metadata +* Captures any response, or full exceptions generated by the handler, and includes them as tracing metadata ### Annotations & Metadata diff --git a/docs/utilities/validation.md b/docs/features/validation.md similarity index 94% rename from docs/utilities/validation.md rename to docs/features/validation.md index 87038ee15a..e320943adb 100644 --- a/docs/utilities/validation.md +++ b/docs/features/validation.md @@ -34,11 +34,6 @@ The `@validator` decorator is a class method decorator that you can use to valid If the validation fails, we will throw a `SchemaValidationError`. -??? note "A note on class method decorators" - The class method decorators in this project follow the experimental implementation enabled via the [`experimentalDecorators` compiler option](https://www.typescriptlang.org/tsconfig#experimentalDecorators) in TypeScript. We will add support for the newer Stage 3 decorators proposal in the next major release. - - All our decorators assume that the method they are decorating is an async method. This means that even when decorating a synchronous method, it will return a promise. If this is not the desired behavior, you can use one of the other patterns to validate your payloads. - === "gettingStartedDecorator.ts" ```typescript hl_lines="1 11-14" diff --git a/docs/getting-started/installation.md b/docs/getting-started/installation.md new file mode 100644 index 0000000000..fe8c350a02 --- /dev/null +++ b/docs/getting-started/installation.md @@ -0,0 +1,32 @@ +--- +title: Installation +description: Installing Powertools for AWS Lambda +--- + + + +You can use Powertools for AWS Lambda (TypeScript) by installing it with your favorite dependency management, or via [Lambda Layers](./lambda-layers.md). + +The toolkit is compatible with both TypeScript and JavaScript code bases, and supports both CommonJS and ES modules. + +All features are available as individual packages, so you can install only the ones you need, for example: + +* **Logger**: `npm i @aws-lambda-powertools/logger`{.copyMe}:clipboard: +* **Metrics**: `npm i @aws-lambda-powertools/metrics`{.copyMe}:clipboard: +* **Tracer**: `npm i @aws-lambda-powertools/tracer`{.copyMe}:clipboard: + +See the [Features](../features/index.md) page for a complete list of available utilities. + +### Extra dependencies + +Some features use additional dependencies like the AWS SDK for JavaScript v3, which might you need to install separately. Below is a list of utilities that use external dependencies, and the packages you need to install to use them. + +| Feature | Install | Default dependency | +| -------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | ------------------- | +| **[Tracer](../features/tracer.md)** | **`npm i @aws-lambda-powertools/tracer`**{.copyMe}:clipboard: | `aws-xray-sdk-core` | +| **[Idempotency](../features/idempotency.md)** | **`npm i @aws-lambda-powertools/idempotency @aws-sdk/client-dynamodb @aws-sdk/lib-dynamodb`**{.copyMe}:clipboard: | | +| **[Parameters (SSM)](../features/parameters.md)** | **`npm i @aws-lambda-powertools/parameters @aws-sdk/client-ssm`**{.copyMe}:clipboard: | | +| **[Parameters (Secrets Manager)](../features/parameters.md)** | **`npm i @aws-lambda-powertools/parameters @aws-sdk/client-secrets-manager`**{.copyMe}:clipboard: | | +| **[Parameters (AppConfig)](../features/parameters.md)** | **`npm i @aws-lambda-powertools/parameters @aws-sdk/client-appconfigdata`**{.copyMe}:clipboard: | | +| **[Parser](../features/parser.md)** | **`npm i @aws-lambda-powertools/parser zod@~3`**{.copyMe}:clipboard: | | +| **[Validation](../features/validation.md)** | **`npm i @aws-lambda-powertools/validation`**{.copyMe}:clipboard: | `ajv` | diff --git a/docs/getting-started/lambda-layers.md b/docs/getting-started/lambda-layers.md new file mode 100644 index 0000000000..056c8dc18c --- /dev/null +++ b/docs/getting-started/lambda-layers.md @@ -0,0 +1,342 @@ +--- +title: Lambda layers +description: Using Powertools for AWS Lambda with Lambda layers +--- + + + +A [Lambda Layer](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html){target="_blank"} is a `.zip` file archive that can contain additional code, pre-packaged dependencies, data, or configuration files. We provide a Lambda Layer for Powertools for AWS Lambda (TypeScript) to help you get started quickly with the library. + +You can add our layer both in the [AWS Lambda Console _(under `Layers`)_](https://docs.aws.amazon.com/lambda/latest/dg/adding-layers.html){target="_blank"}, or via your favorite infrastructure as code framework with the ARN value. You can use the Lambda Layer both with CommonJS and ESM (ECMAScript modules). + +### Layer ARNs + +We publish the Lambda Layer for Powertools for AWS Lambda in all commercial regions and AWS GovCloud (US) regions. + +???+ tip "Spotted a missing region?" + + Open an [issue](https://github.com/aws-powertools/powertools-lambda-typescript/issues/new?template=feature_request.yml&title=Feature%20request%3A%20missing%20Lambda%20layer%20region) in our GitHub repository to request it. + +| Region | Layer ARN | +| ---------------- | -------------------------------------------------------------------------------------------------------------------- | +| `us-east-1` | [arn:aws:lambda:us-east-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | +| `us-east-2` | [arn:aws:lambda:us-east-2:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | +| `us-west-1` | [arn:aws:lambda:us-west-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | +| `us-west-2` | [arn:aws:lambda:us-west-2:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | +| `ap-south-1` | [arn:aws:lambda:ap-south-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | +| `ap-south-2` | [arn:aws:lambda:ap-south-2:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | +| `ap-east-1` | [arn:aws:lambda:ap-east-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | +| `ap-northeast-1` | [arn:aws:lambda:ap-northeast-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | +| `ap-northeast-2` | [arn:aws:lambda:ap-northeast-2:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | +| `ap-northeast-3` | [arn:aws:lambda:ap-northeast-3:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | +| `ap-southeast-1` | [arn:aws:lambda:ap-southeast-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | +| `ap-southeast-2` | [arn:aws:lambda:ap-southeast-2:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | +| `ap-southeast-3` | [arn:aws:lambda:ap-southeast-3:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | +| `ap-southeast-4` | [arn:aws:lambda:ap-southeast-4:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | +| `ap-southeast-5` | [arn:aws:lambda:ap-southeast-5:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | +| `ap-southeast-7` | [arn:aws:lambda:ap-southeast-7:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | +| `eu-central-1` | [arn:aws:lambda:eu-central-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | +| `eu-central-2` | [arn:aws:lambda:eu-central-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | +| `eu-west-1` | [arn:aws:lambda:eu-west-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | +| `eu-west-2` | [arn:aws:lambda:eu-west-2:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | +| `eu-west-3` | [arn:aws:lambda:eu-west-3:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | +| `eu-north-1` | [arn:aws:lambda:eu-north-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | +| `eu-south-1` | [arn:aws:lambda:eu-south-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | +| `eu-south-2` | [arn:aws:lambda:eu-south-2:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | +| `ca-central-1` | [arn:aws:lambda:ca-central-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | +| `ca-west-1` | [arn:aws:lambda:ca-west-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | +| `sa-east-1` | [arn:aws:lambda:sa-east-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | +| `af-south-1` | [arn:aws:lambda:af-south-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | +| `me-south-1` | [arn:aws:lambda:me-south-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | +| `me-central-1` | [arn:aws:lambda:me-central-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | +| `il-central-1` | [arn:aws:lambda:il-central-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | +| `mx-central-1` | [arn:aws:lambda:mx-central-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | +| `us-gov-west-1` | [arn:aws-us-gov:lambda:us-gov-west-1:165093116878:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | +| `us-gov-east-1` | [arn:aws-us-gov:lambda:us-gov-east-1:165087284144:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | + +### Lookup Layer ARN via AWS SSM Parameter Store + +You can also use AWS SSM Parameter Store to dynamically add Powertools for AWS Lambda. The `{version}` placeholder is the semantic version number (e,g. 2.1.0) for a release or `_latest_`. + +For example, to get the ARN for version `2.14.0` in the `eu-west-1` region, run the following command: + +```bash title="AWS CLI command to get Lambda Layer ARN" +aws ssm get-parameter --name /aws/service/powertools/typescript/generic/all/2.14.0 --region eu-west-1 + +# output +Parameter: + ARN: arn:aws:ssm:eu-west-1::parameter/aws/service/powertools/typescript/generic/all/2.14.0 + DataType: text + LastModifiedDate: '2025-02-11T11:08:45.070000+01:00' + Name: /aws/service/powertools/typescript/generic/all/2.14.0 + Type: String + Value: arn:aws:lambda:eu-west-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:20 + Version: 1 +``` + +We currently publish SSM parameters for the following Powertools for AWS Lambda versions in all commercial regions: + +- `/aws/service/powertools/typescript/generic/all/latest`: for the latest version of Powertools for AWS Lambda +- `/aws/service/powertools/typescript/generic/all/{version}`: for a specific version of Powertools for AWS Lambda (e.g. `2.14.0`) + +See the [examples below](#how-to-use-with-infrastructure-as-code) for how to use the SSM parameter in your infrastructure as code. + +### Want to inspect the contents of the Layer? + +The pre-signed URL to download this Lambda Layer will be within `Location` key in the CLI output. The CLI output will also contain the Powertools for AWS Lambda version it contains. + +Change `{aws::region}` to your AWS region, e.g. `eu-west-1`, and run the following command: + +```bash title="AWS CLI command to download Lambda Layer content" +aws lambda get-layer-version-by-arn --arn arn:aws:lambda:{aws::region}:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24 --region {aws::region} + +# output +{ + "Content": {, + "Location": "https://awslambda-eu-west-1-layers.s3.eu-west-1.amazonaws.com/...", + "CodeSha256": "gwGIE8w0JckdDeDCTX6FbWObb2uIDwgiaAq78gMWDyA=", + "CodeSize": 3548324 + }, + "LayerArn": "arn:aws:lambda:eu-west-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2", + "LayerVersionArn": "arn:aws:lambda:eu-west-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24", + "Description": "Powertools for AWS Lambda (TypeScript) version 2.18.0", + "CreatedDate": "2025-04-08T07:38:30.424+0000", + "Version": 24, + "CompatibleRuntimes": [ + "nodejs18.x", + "nodejs20.x", + "nodejs22.x" + ], + "LicenseInfo": "MIT-0", + "CompatibleArchitectures": [ + "arm64", + "x86_64" + ] +} +``` + +### How to use with Infrastructure as Code + +=== "CDK" + + ```typescript hl_lines="14 20" + import { Stack } from 'aws-cdk-lib'; + import { Construct } from 'constructs'; + import { LayerVersion, Function, Runtime, Code } from 'aws-cdk-lib/aws-lambda'; + import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs'; + + export class SampleFunctionWithLayer extends Construct { + constructor(scope: Construct, id: string) { + super(scope, id); + + // Create a Layer with Powertools for AWS Lambda (TypeScript) + const powertoolsLayer = LayerVersion.fromLayerVersionArn( + this, + 'PowertoolsLayer', + `arn:aws:lambda:${Stack.of(this).region}:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24` + ); + + new NodejsFunction(this, 'Function', { + runtime: Runtime.NODEJS_22_X, + // Add the Layer to a Lambda function + layers: [powertoolsLayer], + code: Code.fromInline(`...`), + handler: 'index.handler', + }); + } + } + ``` + + If you use `esbuild` to bundle your code, make sure to exclude `@aws-lambda-powertools/*` and `@aws-sdk/*` from being bundled since the packages are already present the layer: + + ```typescript + new NodejsFunction(this, 'Function', { + ... + bundling: { + externalModules: [ + '@aws-lambda-powertools/*', + '@aws-sdk/*', + ], + } + }); + ``` + + Check the AWS CDK `NodeJsFunction` [documentation](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda_nodejs.BundlingOptions.html#externalmodules) for more details. + + You can also use AWS SSM Parameter Store to dynamically resolve the Layer ARN from SSM Parameter Store and add the toolkit in your code, allowing you to pin to `latest` or a specific Powertools for AWS version. + + ```typescript hl_lines="5 15-17" + import { Stack } from 'aws-cdk-lib'; + import { Construct } from 'constructs'; + import { LayerVersion, Function, Runtime, Code } from 'aws-cdk-lib/aws-lambda'; + import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs'; + import { StringParameter } from 'aws-cdk-lib/aws-ssm'; + + export class SampleFunctionWithLayer extends Construct { + constructor(scope: Construct, id: string) { + super(scope, id); + + // Create a Layer with Powertools for AWS Lambda (TypeScript) + const powertoolsLayer = LayerVersion.fromLayerVersionArn( + this, + 'PowertoolsLayer', + StringParameter.valueForStringParameter(this, 'PowertoolsLayer', { + parameterName: '/aws/service/powertools/typescript/generic/all/latest', + }) + ); + + new NodejsFunction(this, 'Function', { + runtime: Runtime.NODEJS_22_X, + // Add the Layer to a Lambda function + layers: [powertoolsLayer], + code: Code.fromInline(`...`), + handler: 'index.handler', + }); + } + } + ``` + +=== "SAM" + + ```yaml hl_lines="5" + MyLambdaFunction: + Type: AWS::Serverless::Function + Properties: + Layers: + - !Sub arn:aws:lambda:${AWS::Region}:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24 + ``` + + You can also use AWS SSM Parameter Store to dynamically add Powertools for AWS Lambda and resolve the Layer ARN from SSM Parameter Store in your code, allowing you to pin to `latest` or a specific Powertools for AWS Lambda version. + + ```yaml hl_lines="5" + MyLambdaFunction: + Type: AWS::Serverless::Function + Properties: + Layers: + - {{resolve:ssm:/aws/service/powertools/typescript/generic/all/latest}} + ``` + + If you use `esbuild` to bundle your code, make sure to exclude `@aws-lambda-powertools/*` and `@aws-sdk/*` from being bundled since the packages are already present the layer: + + ```yaml hl_lines="5-14" + MyLambdaFunction: + Type: AWS::Serverless::Function + Properties: + ... + Metadata: + # Manage esbuild properties + BuildMethod: esbuild + BuildProperties: + Minify: true + External: + - '@aws-lambda-powertools/*' + - '@aws-sdk/*' + ``` + + Check the [documentation](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-using-build-typescript.html) for more details. + +=== "Serverless framework" + + ```yaml hl_lines="5" + functions: + hello: + handler: lambda_function.lambda_handler + layers: + - arn:aws:lambda:${aws:region}:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24 + ``` + + If you use `esbuild` to bundle your code, make sure to exclude `@aws-lambda-powertools/*` and `@aws-sdk/*` from being bundled since the packages are already present the layer: + + ```yaml + custom: + esbuild: + external: + - '@aws-lambda-powertools/*' + - '@aws-sdk/*' + ``` + + Check the [documentation](https://floydspace.github.io/serverless-esbuild/) for more details. + +=== "Terraform" + + ```terraform hl_lines="18" + terraform { + required_version = "~> 1.0.5" + required_providers { + aws = "~> 3.50.0" + } + } + + provider "aws" { + region = "{aws::region}" + } + + resource "aws_lambda_function" "test_lambda" { + filename = "lambda_function_payload.zip" + function_name = "lambda_function_name" + role = ... + handler = "index.handler" + runtime = "nodejs22.x" + layers = ["arn:aws:lambda:{aws::region}:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24"] + source_code_hash = filebase64sha256("lambda_function_payload.zip") + } + ``` + + You can use [data sources](https://developer.hashicorp.com/terraform/language/data-sources) to resolve the SSM Parameter Store in your code, allowing you to pin to `latest` or a specific Powertools for AWS Lambda version. + + ```terraform + data "aws_ssm_parameter" "powertools_version" { + # Replace {version} with your chosen Powertools for AWS Lambda version or latest + name = "/aws/service/powertools/python/generic/all/latest" + } + + resource "aws_lambda_function" "test_lambda" { + ... + + runtime = "nodejs22.x" + + layers = [data.aws_ssm_parameter.powertools_version.value] + } + ``` + +=== "Pulumi" + + ```typescript hl_lines="11" + import * as pulumi from '@pulumi/pulumi'; + import * as aws from '@pulumi/aws'; + + const role = new aws.iam.Role('role', { + assumeRolePolicy: aws.iam.assumeRolePolicyForPrincipal(aws.iam.Principals.LambdaPrincipal), + managedPolicyArns: [aws.iam.ManagedPolicies.AWSLambdaBasicExecutionRole] + }); + + const lambdaFunction = new aws.lambda.Function('function', { + layers: [ + pulumi.interpolate`arn:aws:lambda:${aws.getRegionOutput().name}:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24` + ], + code: new pulumi.asset.FileArchive('lambda_function_payload.zip'), + tracingConfig: { + mode: 'Active' + }, + runtime: aws.lambda.Runtime.NodeJS22dX, + handler: 'index.handler', + role: role.arn, + architectures: ['x86_64'] + }); + ``` + +=== "Amplify" + + Remember to replace the region with your AWS region, e.g., `eu-west-1`. Amplify Gen 2 currently does not support obtaining the region dynamically. + + ```typescript hl_lines="9 19" + import { defineFunction } from "@aws-amplify/backend"; + + export const myFunction = defineFunction({ + name: "my-function", + layers: { + "@aws-lambda-powertools/*": + "arn:aws:lambda:${AWS::Region}:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24", + }, + }); + ``` diff --git a/docs/getting-started/typescript-settings.md b/docs/getting-started/typescript-settings.md new file mode 100644 index 0000000000..a285a3ffbe --- /dev/null +++ b/docs/getting-started/typescript-settings.md @@ -0,0 +1,46 @@ +--- +title: Typescript Settings +description: Configuration settings for using with TypeScript +--- + + + +While you can use the toolkit with JavaScript, using TypeScript is recommended. + +The toolkit is written in TypeScript with bundled type definitions. We officially support TypeScript 5.0+ and recommend using the latest version to benefit from all features and improvements. + +## TypeScript Configuration + +If you use class method decorators, you must set `experimentalDecorators: true` in your tsconfig.json. This is because we currently support only the legacy decorator syntax. Support for the new decorator syntax will come in our next major release. + +The following `tsconfig.json` file is a good place to start and includes the recommended settings along with some modern TypeScript features. + +```json +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "lib": [ + "es2022" + ], + "declaration": true, + "strict": true, + "noImplicitAny": true, + "strictNullChecks": true, + "noImplicitThis": true, + "alwaysStrict": true, + "noUnusedLocals": false, + "noUnusedParameters": false, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": false, + "inlineSourceMap": true, + "inlineSources": true, + "experimentalDecorators": true, + "strictPropertyInitialization": false + }, + "exclude": [ + "node_modules" + ] +} +``` diff --git a/docs/getting-started/usage-patterns.md b/docs/getting-started/usage-patterns.md new file mode 100644 index 0000000000..5e2eb9c3e3 --- /dev/null +++ b/docs/getting-started/usage-patterns.md @@ -0,0 +1,49 @@ +--- +title: Usage patterns +description: Getting to know the Powertools for AWS Lambda toolkit +--- + + + +Powertools for AWS Lambda (TypeScript) is a collection of utilities designed to help you build serverless applications on AWS. + +The toolkit is modular, so you can pick and choose the utilities you need for your application, but also combine them for a complete solution for your serverless applications. + +## Patterns + +Many of the utilities provided can be used with different patterns, depending on your preferences and the structure of your code. + +### Class Method Decorator + +If you prefer writing your business logic using Object-Oriented Programming (OOP) and TypeScript Classes, the Class Method decorator pattern is a good fit. This approach lets you decorate class methods with Powertools utilities, applying their functionality with minimal code changes. + +This pattern works well when you want to integrate Powertools for AWS into an existing codebase without significant refactoring and with no additional runtime dependencies. + +!!! note + This approach relies on TypeScript's experimental decorator feature, see [TypeScript Settings](./typescript-settings.md) for more information. + +```ts +---8<-- "examples/snippets/getting-started/patterns-decorator.ts" +``` + +All our decorators assume that the method they are decorating is asynchronous. This means that even when decorating a synchronous method, they will return a promise. If this is not the desired behavior, you can use one of the other patterns. + +### Middy.js Middleware + +If your existing codebase relies on the [Middy.js](https://middy.js.org/docs/) middleware engine, you can use the Powertools for AWS Lambda (TypeScript) middleware to integrate with your existing code. This approach is similar to the Class Method decorator pattern but uses the Middy.js middleware engine to apply Powertools utilities. + +!!! note + We guarantee support for Middy.js `v4.x` through `v6.x` versions. + Check Middy.js docs to learn more about [best practices](https://middy.js.org/docs/integrations/lambda-powertools#best-practices){target="_blank"} when working with Powertools for AWS middlewares. + +```ts +---8<-- "examples/snippets/getting-started/patterns-middyjs.ts" +``` + +### Functional Approach + +If you prefer a more functional programming style, you can use the Powertools for AWS Lambda (TypeScript) utilities directly in your code without decorators or middleware. This approach is more verbose but provides the most control over how the utilities are applied. + +```ts +---8<-- "examples/snippets/getting-started/patterns-functional.ts" +``` diff --git a/docs/index.md b/docs/index.md index 15259f66b0..e94605f266 100644 --- a/docs/index.md +++ b/docs/index.md @@ -18,7 +18,7 @@ You can use Powertools for AWS Lambda in both TypeScript and JavaScript code bas Adopt one, a few, or all industry practices. **Progressively**. - [:octicons-arrow-right-24: All features](#features) + [:octicons-arrow-right-24: All features](./features/index.md) - :heart:{ .lg .middle } __Support this project__ @@ -26,7 +26,7 @@ You can use Powertools for AWS Lambda in both TypeScript and JavaScript code bas Become a public reference customer, share your work, contribute, use Lambda Layers, etc. - [:octicons-arrow-right-24: Support](#support-powertools-for-aws-lambda-typescript) + [:octicons-arrow-right-24: Support](#support-powertools-for-aws) - :material-file-code:{ .lg .middle } __Available languages__ @@ -38,363 +38,29 @@ You can use Powertools for AWS Lambda in both TypeScript and JavaScript code bas -## Install - -You can use Powertools for AWS Lambda (TypeScript) by installing it with your favorite dependency management, or via Lambda Layers: - -=== "npmjs.com" - - All features are available as individual packages, so you can install only the ones you need, for example: - - * **Logger**: `npm i @aws-lambda-powertools/logger`{.copyMe}:clipboard: - * **Metrics**: `npm i @aws-lambda-powertools/metrics`{.copyMe}:clipboard: - * **Tracer**: `npm i @aws-lambda-powertools/tracer`{.copyMe}:clipboard: - - ### Extra dependencies - - Some features use additional dependencies like the AWS SDK for JavaScript v3, which might you need to install separately if you are using any of the features below: - - | Feature | Install | Default dependency | - | --------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | ------------------- | - | **[Tracer](./core/tracer.md)** | **`npm i @aws-lambda-powertools/tracer`**{.copyMe}:clipboard: | `aws-xray-sdk-core` | - | **[Idempotency](./utilities/idempotency.md)** | **`npm i @aws-lambda-powertools/idempotency @aws-sdk/client-dynamodb @aws-sdk/lib-dynamodb`**{.copyMe}:clipboard: | | - | **[Parameters (SSM)](./utilities/parameters.md)** | **`npm i @aws-lambda-powertools/parameters @aws-sdk/client-ssm`**{.copyMe}:clipboard: | | - | **[Parameters (Secrets Manager)](./utilities/parameters.md)** | **`npm i @aws-lambda-powertools/parameters @aws-sdk/client-secrets-manager`**{.copyMe}:clipboard: | | - | **[Parameters (AppConfig)](./utilities/parameters.md)** | **`npm i @aws-lambda-powertools/parameters @aws-sdk/client-appconfigdata`**{.copyMe}:clipboard: | | - | **[Parser](./utilities/parser.md)** | **`npm i @aws-lambda-powertools/parser zod@~3`**{.copyMe}:clipboard: | | - -=== "Lambda Layer" - - You can add our layer both in the [AWS Lambda Console _(under `Layers`)_](https://eu-west-1.console.aws.amazon.com/lambda/home#/add/layer){target="_blank"}, or via your favorite infrastructure as code framework with the ARN value. - - For the latter, make sure to replace `{region}` with your AWS region, e.g., `eu-west-1`. - - !!! abstract "" - - __arn:aws:lambda:{region}:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24__{: .copyMe}:clipboard: - - ???+ note "Code snippets for popular infrastructure as code frameworks" - - === "CDK" - - ```typescript hl_lines="14 20" - import { Stack } from 'aws-cdk-lib'; - import { Construct } from 'constructs'; - import { LayerVersion, Function, Runtime, Code } from 'aws-cdk-lib/aws-lambda'; - import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs'; - - export class SampleFunctionWithLayer extends Construct { - constructor(scope: Construct, id: string) { - super(scope, id); - - // Create a Layer with Powertools for AWS Lambda (TypeScript) - const powertoolsLayer = LayerVersion.fromLayerVersionArn( - this, - 'PowertoolsLayer', - `arn:aws:lambda:${Stack.of(this).region}:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24` - ); - - new Function(this, 'Function', { - runtime: Runtime.NODEJS_22_X, - // Add the Layer to a Lambda function - layers: [powertoolsLayer], - code: Code.fromInline(`...`), - handler: 'index.handler', - }); - } - } - ``` - - If you use `esbuild` to bundle your code, make sure to exclude `@aws-lambda-powertools/*` and `@aws-sdk/*` from being bundled since the packages are already present the layer: - - ```typescript - new NodejsFunction(this, 'Function', { - ... - bundling: { - externalModules: [ - '@aws-lambda-powertools/*', - '@aws-sdk/*', - ], - } - }); - ``` - - Check the [documentation](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda_nodejs.BundlingOptions.html#externalmodules) for more details. - - === "SAM" - - ```yaml hl_lines="5" - MyLambdaFunction: - Type: AWS::Serverless::Function - Properties: - Layers: - - !Sub arn:aws:lambda:${AWS::Region}:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24 - ``` - - You can also use AWS SSM Parameter Store to dynamically add Powertools for AWS Lambda. The `{version}` placeholder is the semantic version number (e,g. 2.1.0) for a release or `_latest_`. - - ```yaml hl_lines="5" - MyLambdaFunction: - Type: AWS::Serverless::Function - Properties: - Layers: - - {{resolve:ssm:/aws/service/powertools/typescript/generic/all/{version}}} - ``` - - If you use `esbuild` to bundle your code, make sure to exclude `@aws-lambda-powertools/*` and `@aws-sdk/*` from being bundled since the packages are already present the layer: - - ```yaml hl_lines="5-14" - MyLambdaFunction: - Type: AWS::Serverless::Function - Properties: - ... - Metadata: - # Manage esbuild properties - BuildMethod: esbuild - BuildProperties: - Minify: true - External: - - '@aws-lambda-powertools/*' - - '@aws-sdk/*' - ``` - - Check the [documentation](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-using-build-typescript.html) for more details. - - === "Serverless framework" - - ```yaml hl_lines="5" - functions: - hello: - handler: lambda_function.lambda_handler - layers: - - arn:aws:lambda:${aws:region}:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24 - ``` - - If you use `esbuild` to bundle your code, make sure to exclude `@aws-lambda-powertools/*` and `@aws-sdk/*` from being bundled since the packages are already present the layer: - - ```yaml - custom: - esbuild: - external: - - '@aws-lambda-powertools/*' - - '@aws-sdk/*' - ``` - - Check the [documentation](https://floydspace.github.io/serverless-esbuild/) for more details. - - === "Terraform" - - ```terraform hl_lines="18" - terraform { - required_version = "~> 1.0.5" - required_providers { - aws = "~> 3.50.0" - } - } - - provider "aws" { - region = "{aws::region}" - } - - resource "aws_lambda_function" "test_lambda" { - filename = "lambda_function_payload.zip" - function_name = "lambda_function_name" - role = ... - handler = "index.handler" - runtime = "nodejs22.x" - layers = ["arn:aws:lambda:{aws::region}:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24"] - source_code_hash = filebase64sha256("lambda_function_payload.zip") - } - ``` - - You can use [data sources](https://developer.hashicorp.com/terraform/language/data-sources) to resolve the SSM Parameter Store in your code, allowing you to pin to `_latest_` or a specific Powertools for AWS Lambda version. - - ```terraform - data "aws_ssm_parameter" "powertools_version" { - # Replace {version} with your chosen Powertools for AWS Lambda version or latest - name = "/aws/service/powertools/python/generic/all/{version}" - } - - resource "aws_lambda_function" "test_lambda" { - ... - - runtime = "nodejs22.x" - - layers = [data.aws_ssm_parameter.powertools_version.value] - } - ``` - - === "Pulumi" - - ```typescript hl_lines="11" - import * as pulumi from '@pulumi/pulumi'; - import * as aws from '@pulumi/aws'; - - const role = new aws.iam.Role('role', { - assumeRolePolicy: aws.iam.assumeRolePolicyForPrincipal(aws.iam.Principals.LambdaPrincipal), - managedPolicyArns: [aws.iam.ManagedPolicies.AWSLambdaBasicExecutionRole] - }); - - const lambdaFunction = new aws.lambda.Function('function', { - layers: [ - pulumi.interpolate`arn:aws:lambda:${aws.getRegionOutput().name}:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24` - ], - code: new pulumi.asset.FileArchive('lambda_function_payload.zip'), - tracingConfig: { - mode: 'Active' - }, - runtime: aws.lambda.Runtime.NodeJS22dX, - handler: 'index.handler', - role: role.arn, - architectures: ['x86_64'] - }); - ``` - - === "Amplify" - - Remember to replace the region with your AWS region, e.g., `eu-west-1`. Amplify Gen 2 currently does not support obtaining the region dynamically. - - ```typescript hl_lines="9 19" - import { defineFunction } from "@aws-amplify/backend"; - - export const myFunction = defineFunction({ - name: "my-function", - layers: { - "@aws-lambda-powertools/*": - "arn:aws:lambda:${AWS::Region}:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24", - }, - }); - ``` - -=== "Layer in GovCloud" - - We also provide layers in two GovCloud regions: - - !!! abstract "" - - * __arn:aws-us-gov:lambda:us-gov-east-1:165087284144:layer:AWSLambdaPowertoolsTypeScriptV2:24__{: .copyMe}:clipboard: - * __arn:aws-us-gov:lambda:us-gov-west-1:165093116878:layer:AWSLambdaPowertoolsTypeScriptV2:24__{: .copyMe}:clipboard: - -### Lambda Layer - -[Lambda Layer](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html){target="_blank"} is a `.zip` file archive that can contain additional code, pre-packaged dependencies, data, or configuration files. We compile and optimize [all dependencies](#install) to achieve an optimal build. - -You can use the Lambda Layer both with CommonJS and ESM (ECMAScript modules) for Node.js 18.x and newer runtimes. - -??? note "Click to expand and copy any regional Lambda Layer ARN" - | Region | Layer ARN | - | ---------------- | ------------------------------------------------------------------------------------------------------------- | - | `us-east-1` | [arn:aws:lambda:us-east-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | - | `us-east-2` | [arn:aws:lambda:us-east-2:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | - | `us-west-1` | [arn:aws:lambda:us-west-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | - | `us-west-2` | [arn:aws:lambda:us-west-2:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | - | `ap-south-1` | [arn:aws:lambda:ap-south-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | - | `ap-south-2` | [arn:aws:lambda:ap-south-2:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | - | `ap-east-1` | [arn:aws:lambda:ap-east-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | - | `ap-northeast-1` | [arn:aws:lambda:ap-northeast-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | - | `ap-northeast-2` | [arn:aws:lambda:ap-northeast-2:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | - | `ap-northeast-3` | [arn:aws:lambda:ap-northeast-3:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | - | `ap-southeast-1` | [arn:aws:lambda:ap-southeast-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | - | `ap-southeast-2` | [arn:aws:lambda:ap-southeast-2:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | - | `ap-southeast-3` | [arn:aws:lambda:ap-southeast-3:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | - | `ap-southeast-4` | [arn:aws:lambda:ap-southeast-4:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | - | `ap-southeast-5` | [arn:aws:lambda:ap-southeast-5:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | - | `ap-southeast-7` | [arn:aws:lambda:ap-southeast-7:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | - | `eu-central-1` | [arn:aws:lambda:eu-central-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | - | `eu-central-2` | [arn:aws:lambda:eu-central-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | - | `eu-west-1` | [arn:aws:lambda:eu-west-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | - | `eu-west-2` | [arn:aws:lambda:eu-west-2:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | - | `eu-west-3` | [arn:aws:lambda:eu-west-3:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | - | `eu-north-1` | [arn:aws:lambda:eu-north-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | - | `eu-south-1` | [arn:aws:lambda:eu-south-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | - | `eu-south-2` | [arn:aws:lambda:eu-south-2:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | - | `ca-central-1` | [arn:aws:lambda:ca-central-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | - | `ca-west-1` | [arn:aws:lambda:ca-west-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | - | `sa-east-1` | [arn:aws:lambda:sa-east-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | - | `af-south-1` | [arn:aws:lambda:af-south-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | - | `me-south-1` | [arn:aws:lambda:me-south-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | - | `me-central-1` | [arn:aws:lambda:me-central-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | - | `il-central-1` | [arn:aws:lambda:il-central-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | - | `mx-central-1` | [arn:aws:lambda:mx-central-1:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24](#){: .copyMe}:clipboard: | - -**Want to inspect the contents of the Layer?** - -The pre-signed URL to download this Lambda Layer will be within `Location` key in the CLI output. The CLI output will also contain the Powertools for AWS Lambda version it contains. - -Change `{aws::region}` to your AWS region, e.g. `eu-west-1`, and run the following command: - -```bash title="AWS CLI command to download Lambda Layer content" -aws lambda get-layer-version-by-arn --arn arn:aws:lambda:{aws::region}:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24 --region {aws::region} -``` - -## Instrumentation - -Many of the utilities provided by Powertools for AWS Lambda (TypeScript) can be used with different programming paradigms: - -- **Middy** middleware. It is the best choice if your existing code base relies on the [Middy.js](https://middy.js.org/docs/) middleware engine. Powertools for AWS Lambda (TypeScript) offers compatible Middy middleware to make this integration seamless. -- **Method decorator**. Use [TypeScript method decorators](https://www.typescriptlang.org/docs/handbook/decorators.html#method-decorators) if you prefer writing your business logic using [TypeScript Classes](https://www.typescriptlang.org/docs/handbook/classes.html). If you aren’t using Classes, this requires the most significant refactoring. -- **Manually**. It provides the most granular control. It’s the most verbose approach, with the added benefit of no additional dependency and no refactoring to TypeScript Classes. - -The examples in this documentation will feature all the approaches described above wherever applicable. +## Features -## Examples +Powertools for AWS Lambda (TypeScript) is built as a modular toolkit, so you can pick and choose the utilities you want to use. The following table lists the available utilities, and links to their documentation. -You can find examples of how to use Powertools for AWS Lambda (TypeScript) in the [examples](https://github.com/aws-powertools/powertools-lambda-typescript/tree/main/examples/app){target="_blank"} directory. The application is a simple REST API that can be deployed via either AWS CDK or AWS SAM. +| Utility | Description | +| -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- ------------------------------- | +| [Tracer](./features/tracer.md) | Decorators and utilities to trace Lambda function handlers, and both synchronous and asynchronous functions | +| [Logger](./features/logger.md) | Structured logging made easier, and a middleware to enrich structured logging with key Lambda context details | +| [Metrics](./features/metrics.md) | Custom Metrics created asynchronously via CloudWatch Embedded Metric Format (EMF) | +| [Parameters](./features/parameters.md) | High-level functions to retrieve one or more parameters from AWS SSM Parameter Store, AWS Secrets Manager, AWS AppConfig, and Amazon DynamoDB | +| [Idempotency](./features/idempotency.md) | Class method decorator, Middy middleware, and function wrapper to make your Lambda functions idempotent and prevent duplicate execution based on payload content. | +| [Batch Processing](./features/batch.md) | Utility to handle partial failures when processing batches from Amazon SQS, Amazon Kinesis Data Streams, and Amazon DynamoDB Streams. | +| [JMESPath Functions](./features/jmespath.md) | Built-in JMESPath functions to easily deserialize common encoded JSON payloads in Lambda functions. | +| [Parser](./features/parser.md) | Utility to parse and validate AWS Lambda event payloads using Zod, a TypeScript-first schema declaration and validation library. | +| [Validation](./features/validation.md) | JSON Schema validation for events and responses, including JMESPath support to unwrap events before validation. | -If instead you want to see Powertools for AWS Lambda (TypeScript) in slightly different use cases, check the [Serverless TypeScript Demo](https://github.com/aws-samples/serverless-typescript-demo) or the [AWS Lambda performance tuning](https://github.com/aws-samples/optimizations-for-lambda-functions) repository. Both demos use Powertools for AWS Lambda (TypeScript) as well as demonstrating other common techniques for Lambda functions written in TypeScript. +## Examples -## Features +You can find examples of how to use Powertools for AWS Lambda (TypeScript) in the [examples](https://github.com/aws-powertools/powertools-lambda-typescript/tree/main/examples){target="_blank"} directory, which contains both code snippets for specific use cases, as well as a full example application. + +If instead you want to see Powertools for AWS Lambda (TypeScript) in a more involved context, check the [Powertools for AWS workshop](https://github.com/aws-samples/powertools-for-aws-lambda-workshop/tree/main/functions/typescript) where we demonstrate how to use toolkit in a more complex application. -Core utilities such as Tracing, Logging, and Metrics will be available across all Powertools for AWS Lambda languages. Additional utilities are subjective to each language ecosystem and customer demand. - -| Utility | Description | -| ----------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [Tracer](./core/tracer.md) | Decorators and utilities to trace Lambda function handlers, and both synchronous and asynchronous functions | -| [Logger](./core/logger.md) | Structured logging made easier, and a middleware to enrich structured logging with key Lambda context details | -| [Metrics](./core/metrics.md) | Custom Metrics created asynchronously via CloudWatch Embedded Metric Format (EMF) | -| [Parameters](./utilities/parameters.md) | High-level functions to retrieve one or more parameters from AWS SSM Parameter Store, AWS Secrets Manager, AWS AppConfig, and Amazon DynamoDB | -| [Idempotency](./utilities/idempotency.md) | Class method decorator, Middy middleware, and function wrapper to make your Lambda functions idempotent and prevent duplicate execution based on payload content. | -| [Batch Processing](./utilities/batch.md) | Utility to handle partial failures when processing batches from Amazon SQS, Amazon Kinesis Data Streams, and Amazon DynamoDB Streams. | -| [Parser](./utilities/parser.md) | Utility to parse and validate AWS Lambda event payloads using Zod, a TypeScript-first schema declaration and validation library. | - -## Environment variables - -???+ info - Explicit parameters take precedence over environment variables - -| Environment variable | Description | Utility | Default | -| -------------------------------------------- |------------------------------------------------------------------------------------------| --------------------------------------- |-------------------------------------------------| -| **POWERTOOLS_SERVICE_NAME** | Set service name used for tracing namespace, metrics dimension and structured logging | All | `service_undefined` | -| **POWERTOOLS_METRICS_NAMESPACE** | Set namespace used for metrics | [Metrics](core/metrics.md) | `default_namespace` | -| **POWERTOOLS_METRICS_FUNCTION_NAME** | Function name used as dimension for the `ColdStart` metric | [Metrics](core/metrics.md) | [See docs](core/metrics.md#setting-function-name) | -| **POWERTOOLS_METRICS_ENABLED** | Explicitly disables emitting metrics to stdout | [Metrics](core/metrics.md) | `true` | -| **POWERTOOLS_TRACE_ENABLED** | Explicitly disables tracing | [Tracer](core/tracer.md) | `true` | -| **POWERTOOLS_TRACER_CAPTURE_RESPONSE** | Capture Lambda or method return as metadata. | [Tracer](core/tracer.md) | `true` | -| **POWERTOOLS_TRACER_CAPTURE_ERROR** | Capture Lambda or method exception as metadata. | [Tracer](core/tracer.md) | `true` | -| **POWERTOOLS_TRACER_CAPTURE_HTTPS_REQUESTS** | Capture HTTP(s) requests as segments. | [Tracer](core/tracer.md) | `true` | -| **POWERTOOLS_LOGGER_LOG_EVENT** | Log incoming event | [Logger](core/logger.md) | `false` | -| **POWERTOOLS_LOGGER_SAMPLE_RATE** | Debug log sampling | [Logger](core/logger.md) | `0` | -| **POWERTOOLS_DEV** | Pretty-print logs, disable metrics flushing, and disable traces - use for dev only | See section below | `false` | -| **POWERTOOLS_LOG_LEVEL** | Sets how verbose Logger should be, from the most verbose to the least verbose (no logs) | [Logger](core/logger.md) | `INFO` | -| **POWERTOOLS_PARAMETERS_MAX_AGE** | Adjust how long values are kept in cache (in seconds) | [Parameters](utilities/parameters.md) | `5` | -| **POWERTOOLS_PARAMETERS_SSM_DECRYPT** | Set whether to decrypt or not values retrieved from AWS Systems Manager Parameters Store | [Parameters](utilities/parameters.md) | `false` | -| **POWERTOOLS_IDEMPOTENCY_DISABLED** | Disable the Idempotency logic without changing your code, useful for testing | [Idempotency](utilities/idempotency.md) | `false` | - -Each Utility page provides information on example values and allowed values. - -### Optimizing for non-production environments - -Whether you're prototyping locally or against a non-production environment, you can use `POWERTOOLS_DEV` to increase verbosity across multiple utilities. - -When `POWERTOOLS_DEV` is set to a truthy value (`1`, `true`), it'll have the following effects: - -| Utility | Effect | -| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| __Logger__ | Increase JSON indentation to 4 and uses global `console` to emit logs to ease testing and local debugging when running functions locally. However, Amazon CloudWatch Logs view will degrade as each new line is treated as a new message | -| __Tracer__ | Disables tracing operations in non-Lambda environments. This already happens automatically in the Tracer utility | -| __Metrics__ | Disables emitting metrics to stdout. Can be overridden by setting `POWERTOOLS_METRICS_ENABLED` to `true` | - -## Support Powertools for AWS Lambda (TypeScript) +## Support Powertools for AWS There are many ways you can help us gain future investments to improve everyone's experience: @@ -489,7 +155,7 @@ Knowing which companies are using this library is important to help prioritize t !!! note "Layers help us understand who uses Powertools for AWS Lambda (TypeScript) in a non-intrusive way." -When [using Layers](#lambda-layer), you can add Powertools for AWS Lambda (TypeScript) as a dev dependency to not impact the development process. For Layers, we pre-package all dependencies, compile and optimize for storage. +When [using Layers](./getting-started/lambda-layers.md), you can add Powertools for AWS Lambda (TypeScript) as a dev dependency to not impact the development process. For Layers, we pre-package all dependencies, compile and optimize for storage. ## Tenets diff --git a/docs/upgrade.md b/docs/upgrade.md index c55656a157..e135a0f7df 100644 --- a/docs/upgrade.md +++ b/docs/upgrade.md @@ -22,7 +22,7 @@ V2 is focused on official support for ESM (ECMAScript modules). We've made other | **ESM support** | Added ESM support via dual CommonJS and ESM bundling, enabling top-level `await` and tree-shaking. | - | | **Middy.js** | Updated import path for Middy.js middlewares to leverage subpath exports - i.e. `@aws-lambda-powertools/tracer/middleware`. | Yes | | **Types imports** | Updated import path for TypeScript types to leverage subpath exports - i.e. `@aws-lambda-powertools/logger/types`. | Yes | -| **Logger** | Changed [log sampling](./core/logger.md#sampling-debug-logs) to dynamically switch log level to `DEBUG` on a percentage of requests. | - | +| **Logger** | Changed [log sampling](./features/logger.md#sampling-debug-logs) to dynamically switch log level to `DEBUG` on a percentage of requests. | - | | **Logger** | Updated [custom log formatter](#custom-log-formatter) to include standard as well as persistent keys. | Yes | | **Logger** | Removed `ContextExamples` from `@aws-lambda-powertools/commons` package. | Yes | | **Logger and Tracer** | Removed deprecated `createLogger` and `createTracer` helper functions in favor of direct instantiation. | Yes | @@ -32,7 +32,7 @@ V2 is focused on official support for ESM (ECMAScript modules). We've made other Before you start, we suggest making a copy of your current working project or create a new git branch. 1. Upgrade Node.js to v18 or higher, Node.js v20 is recommended. -2. Ensure that you have the latest Powertools for AWS Lambda (TypeScript) version via [Lambda Layer](./index.md#lambda-layer) or npm. +2. Ensure that you have the latest Powertools for AWS Lambda (TypeScript) version via [Lambda Layer](./getting-started/lambda-layers.md) or npm. 3. Review the following sections to confirm whether they apply to your codebase. ## ESM support @@ -198,7 +198,7 @@ Below is an example of how to configure your `.eslintrc.json` file: ### Log sampling -!!! note "Disregard if you are not using the [log sampling feature](./core/logger.md#sampling-debug-logs)." +!!! note "Disregard if you are not using the [log sampling feature](./features/logger.md#sampling-debug-logs)." In v1, log sampling implementation was inconsistent from other Powertools for AWS Lambda languages _(Python, .NET, and Java)_. @@ -213,11 +213,11 @@ Logger `sampleRateValue` **continues** to determine the percentage of concurrent ### Custom log formatter -!!! note "Disregard if you are not customizing log output with a [custom log formatter](./core/logger.md#custom-log-formatter)." +!!! note "Disregard if you are not customizing log output with a [custom log formatter](./features/logger.md#custom-log-formatter)." -In v1, `Logger` exposed the [standard](./core/logger.md#standard-structured-keys) as a single argument, _e.g., `formatAttributes(attributes: UnformattedAttributes)`_. It expected a plain object with keys and values you wanted in the final log output. +In v1, `Logger` exposed the [standard](./features/logger.md#standard-structured-keys) as a single argument, _e.g., `formatAttributes(attributes: UnformattedAttributes)`_. It expected a plain object with keys and values you wanted in the final log output. -In v2, you have more control over **standard** (`attributes`) and [**custom keys**](./core/logger.md#appending-additional-keys) (`additionalLogAttributes`) in the `formatAttributes` method. Also, you now return a `LogItem` object to increase type safety when defining the final log output. +In v2, you have more control over **standard** (`attributes`) and [**custom keys**](./features/logger.md#appending-additional-keys) (`additionalLogAttributes`) in the `formatAttributes` method. Also, you now return a `LogItem` object to increase type safety when defining the final log output. === "Before" @@ -305,7 +305,7 @@ In v2, you have more control over **standard** (`attributes`) and [**custom keys export { MyCompanyLogFormatter }; ``` - 1. This new argument contains all [your custom keys](./core/logger.md#appending-additional-keys). + 1. This new argument contains all [your custom keys](./features/logger.md#appending-additional-keys). 2. `LogItem` is the new return object instead of a plain object. 3. If you prefer adding at the initialization, use:

**`LogItem({persistentAttributes: additionalLogAttributes, attributes: baseAttributes})`** diff --git a/examples/snippets/getting-started/patterns-decorator.ts b/examples/snippets/getting-started/patterns-decorator.ts new file mode 100644 index 0000000000..5af62e149b --- /dev/null +++ b/examples/snippets/getting-started/patterns-decorator.ts @@ -0,0 +1,20 @@ +import type { LambdaInterface } from '@aws-lambda-powertools/commons/types'; +import { Logger } from '@aws-lambda-powertools/logger'; +import { Metrics } from '@aws-lambda-powertools/metrics'; +import { Tracer } from '@aws-lambda-powertools/tracer'; +import type { Context } from 'aws-lambda'; + +const logger = new Logger(); +const tracer = new Tracer(); +const metrics = new Metrics(); + +class Lambda implements LambdaInterface { + @tracer.captureLambdaHandler() + @logger.injectLambdaContext() + @metrics.logMetrics() + async handler(_event: unknown, _context: Context) { + // Your business logic here + } +} +const lambda = new Lambda(); +export const handler = lambda.handler.bind(lambda); diff --git a/examples/snippets/getting-started/patterns-functional.ts b/examples/snippets/getting-started/patterns-functional.ts new file mode 100644 index 0000000000..ad3a752ae5 --- /dev/null +++ b/examples/snippets/getting-started/patterns-functional.ts @@ -0,0 +1,27 @@ +import { Logger } from '@aws-lambda-powertools/logger'; +import { Metrics } from '@aws-lambda-powertools/metrics'; +import { Tracer } from '@aws-lambda-powertools/tracer'; +import type { Context } from 'aws-lambda'; + +const logger = new Logger(); +const tracer = new Tracer(); +const metrics = new Metrics(); + +export const handler = async (event: unknown, context: Context) => { + logger.addContext(context); + logger.logEventIfEnabled(event); + + const subsegment = tracer.getSegment()?.addNewSubsegment('#### handler'); + + try { + // Your business logic here + throw new Error('An error occurred'); + } catch (error) { + logger.error('Error occurred', { error }); + tracer.addErrorAsMetadata(error); + throw error; + } finally { + subsegment?.close(); + metrics.publishStoredMetrics(); + } +}; diff --git a/examples/snippets/getting-started/patterns-middyjs.ts b/examples/snippets/getting-started/patterns-middyjs.ts new file mode 100644 index 0000000000..ece2f97266 --- /dev/null +++ b/examples/snippets/getting-started/patterns-middyjs.ts @@ -0,0 +1,19 @@ +import { Logger } from '@aws-lambda-powertools/logger'; +import { injectLambdaContext } from '@aws-lambda-powertools/logger/middleware'; +import { Metrics } from '@aws-lambda-powertools/metrics'; +import { logMetrics } from '@aws-lambda-powertools/metrics/middleware'; +import { Tracer } from '@aws-lambda-powertools/tracer'; +import { captureLambdaHandler } from '@aws-lambda-powertools/tracer/middleware'; +import middy from '@middy/core'; + +const logger = new Logger(); +const tracer = new Tracer(); +const metrics = new Metrics(); + +export const handler = middy() + .use(captureLambdaHandler(tracer)) + .use(injectLambdaContext(logger)) + .use(logMetrics(metrics)) + .handler(async (event: unknown) => { + // Your business logic here + }); diff --git a/mkdocs.yml b/mkdocs.yml index 5bfc63b52c..28ce8b07a2 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -32,22 +32,29 @@ watch: [ nav: - Homepage: - index.md - - Changelog: changelog.md + - Getting Started: + - Installation: getting-started/installation.md + - Usage patterns: getting-started/usage-patterns.md + - TypeScript settings: getting-started/typescript-settings.md + - Lambda layers: getting-started/lambda-layers.md + - Workshop: https://s12d.com/powertools-for-aws-lambda-workshop" target="_blank + - Features: + - features/index.md + - features/tracer.md + - features/logger.md + - features/metrics.md + - features/parameters.md + - features/idempotency.md + - features/batch.md + - features/jmespath.md + - features/parser.md + - features/validation.md + - Environment variables: environment-variables.md - Upgrade guide: upgrade.md - - We Made This (Community): we_made_this.md - - Workshop: https://s12d.com/powertools-for-aws-lambda-workshop" target="_blank + - Community Content: we_made_this.md - Roadmap: roadmap.md - - Features: - - core/tracer.md - - core/logger.md - - core/metrics.md - - utilities/parameters.md - - utilities/idempotency.md - - utilities/batch.md - - utilities/jmespath.md - - utilities/parser.md - - utilities/validation.md - - API reference: api" + - Changelog: changelog.md + - API reference: api/" target="_blank - Processes: - Roadmap: roadmap.md - Versioning policy: versioning.md