Skip to content

Commit 3f9cfd8

Browse files
dreamorosiam29d
andauthored
docs(commons): refresh API docs & README (#2452)
* docs(commons): refresh API docs & README * chore: fix interface in tests --------- Co-authored-by: Alexander Schueren <[email protected]>
1 parent 242b5e2 commit 3f9cfd8

18 files changed

+451
-145
lines changed

packages/commons/README.md

+82-63
Original file line numberDiff line numberDiff line change
@@ -4,73 +4,96 @@ Powertools for AWS Lambda (TypeScript) is a developer toolkit to implement Serve
44

55
You can use the library in both TypeScript and JavaScript code bases.
66

7-
> Also available in [Python](https://github.com/aws-powertools/powertools-lambda-python), [Java](https://github.com/aws-powertools/powertools-lambda-java), and [.NET](https://github.com/aws-powertools/powertools-lambda-dotnet).
7+
## Intro
88

9-
**[Documentation](https://docs.powertools.aws.dev/lambda/typescript/)** | **[npm](https://www.npmjs.com/org/aws-lambda-powertools)** | **[Roadmap](https://docs.powertools.aws.dev/lambda/typescript/latest/roadmap)** | **[Examples](https://github.com/aws-powertools/powertools-lambda-typescript/tree/main/examples)**
9+
The Commons package contains a set of utilities that are shared across one or more Powertools for AWS Lambda (TypeScript) utilities. Some of these utilities can also be used independently in your AWS Lambda functions.
1010

11-
## Table of contents <!--- omit in toc -->
11+
## Usage
1212

13-
- [Table of contents ](#table-of-contents-)
14-
- [Features](#features)
15-
- [Getting started](#getting-started)
16-
- [Installation](#installation)
17-
- [Examples](#examples)
18-
- [Demo applications](#demo-applications)
19-
- [Contribute](#contribute)
20-
- [Roadmap](#roadmap)
21-
- [Connect](#connect)
22-
- [How to support Powertools for AWS Lambda (TypeScript)?](#how-to-support-powertools-for-aws-lambda-typescript)
23-
- [Becoming a reference customer](#becoming-a-reference-customer)
24-
- [Sharing your work](#sharing-your-work)
25-
- [Using Lambda Layer](#using-lambda-layer)
26-
- [Credits](#credits)
27-
- [License](#license)
13+
To get started, install the utility by running:
2814

29-
## Features
30-
31-
* **[Tracer](https://docs.powertools.aws.dev/lambda/typescript/latest/core/tracer/)** - Utilities to trace Lambda function handlers, and both synchronous and asynchronous functions
32-
* **[Logger](https://docs.powertools.aws.dev/lambda/typescript/latest/core/logger/)** - Structured logging made easier, and a middleware to enrich log items with key details of the Lambda context
33-
* **[Metrics](https://docs.powertools.aws.dev/lambda/typescript/latest/core/metrics/)** - Custom Metrics created asynchronously via CloudWatch Embedded Metric Format (EMF)
34-
* **[Parameters](https://docs.powertools.aws.dev/lambda/typescript/latest/utilities/parameters/)** - High-level functions to retrieve one or more parameters from AWS SSM, Secrets Manager, AppConfig, and DynamoDB
35-
* **[Idempotency](https://docs.powertools.aws.dev/lambda/typescript/latest/utilities/idempotency/)** - Class method decorator, Middy middleware, and function wrapper to make your Lambda functions idempotent and prevent duplicate execution based on payload content
36-
* **[Batch processing](https://docs.powertools.aws.dev/lambda/typescript/latest/utilities/batch/)** - Utility to handle partial failures when processing batches from Amazon SQS, Amazon Kinesis Data Streams, and Amazon DynamoDB Streams.
15+
```sh
16+
npm i @aws-lambda-powertools/commons
17+
```
3718

38-
## Getting started
19+
### Type utils
3920

40-
Find the complete project's [documentation here](https://docs.powertools.aws.dev/lambda/typescript).
21+
When working with different objects and values, you may want to do runtime type checks. The utility comes with a set of type utilities that you can use to check the type of an object or value.
4122

42-
### Installation
23+
```typescript
24+
import { isRecord } from '@aws-lambda-powertools/commons/typeUtils';
25+
import { isString } from '@aws-lambda-powertools/commons/typeUtils';
26+
import { isTruthy } from '@aws-lambda-powertools/commons/typeUtils';
4327

44-
The Powertools for AWS Lambda (TypeScript) utilities follow a modular approach, similar to the official [AWS SDK v3 for JavaScript](https://github.com/aws/aws-sdk-js-v3).
4528

46-
Each TypeScript utility is installed as standalone npm package.
29+
const value = { key: 'value' };
30+
if (isRecord(value)) {
31+
// value is a record
32+
}
4733

48-
Install all three core utilities at once with this single command:
34+
const stringValue = 'string';
35+
if (isString(stringValue)) {
36+
// stringValue is a string
37+
}
4938

50-
```shell
51-
npm install @aws-lambda-powertools/logger @aws-lambda-powertools/tracer @aws-lambda-powertools/metrics
39+
const truthyValue = 'true';
40+
if (isTruthy(truthyValue)) {
41+
// truthyValue is truthy
42+
}
5243
```
5344

54-
Or refer to the installation guide of each utility:
45+
Here's a full list of type utilities available in the package:
46+
47+
- [`isInteger`](https://docs.powertools.aws.dev/lambda/typescript/latest/api/functions/_aws_lambda_powertools_commons.isIntegerNumber.html)
48+
- [`isNull`](https://docs.powertools.aws.dev/lambda/typescript/latest/api/functions/_aws_lambda_powertools_commons.isNull.html)
49+
- [`isNullOrUndefined`](https://docs.powertools.aws.dev/lambda/typescript/latest/api/functions/_aws_lambda_powertools_commons.isNullOrUndefined.html)
50+
- [`isNumber`](https://docs.powertools.aws.dev/lambda/typescript/latest/api/functions/_aws_lambda_powertools_commons.isNumber.html)
51+
- [`isRecord`](https://docs.powertools.aws.dev/lambda/typescript/latest/api/functions/_aws_lambda_powertools_commons.isRecord.html)
52+
- [`isStrictEqual`](https://docs.powertools.aws.dev/lambda/typescript/latest/api/functions/_aws_lambda_powertools_commons.isStrictEqual.html)
53+
- [`isString`](https://docs.powertools.aws.dev/lambda/typescript/latest/api/functions/_aws_lambda_powertools_commons.isString.html)
54+
- [`isTruthy`](https://docs.powertools.aws.dev/lambda/typescript/latest/api/functions/_aws_lambda_powertools_commons.isTruthy.html)
55+
56+
Many of these utilities also double as type guards, which you can use to narrow down the type of an object or value.
57+
58+
### Base64 utils
59+
60+
When working with Base64-encoded data, you can use the `fromBase64` utilities to quickly decode data and convert it to a `Uint8Array`.
61+
62+
```typescript
5563

56-
👉 [Installation guide for the **Tracer** utility](https://docs.powertools.aws.dev/lambda/typescript/latest/core/tracer#getting-started)
64+
import { fromBase64 } from '@aws-lambda-powertools/commons/utils/base64';
5765

58-
👉 [Installation guide for the **Logger** utility](https://docs.powertools.aws.dev/lambda/typescript/latest/core/logger#getting-started)
66+
const encodedValue = 'aGVsbG8gd29ybGQ=';
5967

60-
👉 [Installation guide for the **Metrics** utility](https://docs.powertools.aws.dev/lambda/typescript/latest/core/metrics#getting-started)
68+
const decoded = fromBase64(encodedValue);
69+
// new Uint8Array([ 97, 71, 86, 115, 98, 71, 56, 103, 100, 50, 57, 121, 98, 71, 81, 61 ]);
70+
```
71+
72+
### JSON type utils
6173

62-
👉 [Installation guide for the **Parameters** utility](https://docs.powertools.aws.dev/lambda/typescript/latest/utilities/parameters/#getting-started)
74+
In some cases, you may want to define a type for a JSON object or value. The utility comes with a set of types that you can use to define your JSON objects.
6375

64-
### Examples
76+
```typescript
77+
import type { JSONValue, JSONObject, JSONArray } from '@aws-lambda-powertools/commons';
78+
```
6579

66-
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) directory. The application is a simple REST API that can be deployed via either AWS CDK or AWS SAM.
80+
### Lambda interface
6781

68-
### Demo applications
82+
When using object-oriented patterns to define your Lambda handlers, you can use the `LambdaHandler` interface to define the shape of your handler methods.
6983

70-
The [Serverless TypeScript Demo](https://github.com/aws-samples/serverless-typescript-demo) shows how to use Powertools for AWS Lambda (TypeScript).
71-
You can find instructions on how to deploy and load test this application in the [repository](https://github.com/aws-samples/serverless-typescript-demo).
84+
```typescript
85+
import type { Context } from 'aws-lambda';
86+
import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
7287

73-
The [AWS Lambda performance tuning](https://github.com/aws-samples/optimizations-for-lambda-functions) repository also uses Powertools for AWS Lambda (TypeScript) as well as demonstrating other performance tuning techniques for Lambda functions written in TypeScript.
88+
class Lambda implements LambdaInterface {
89+
public handler = async (event: unknown, context: Context) => {
90+
// Your handler code here
91+
}
92+
}
93+
94+
const handlerClass = new Lambda();
95+
export const handler = lambda.handler.bind(lambda);
96+
```
7497

7598
## Contribute
7699

@@ -83,8 +106,8 @@ Help us prioritize upcoming functionalities or utilities by [upvoting existing R
83106

84107
## Connect
85108

86-
* **Powertools for AWS Lambda on Discord**: `#typescript` - **[Invite link](https://discord.gg/B8zZKbbyET)**
87-
* **Email**: [email protected]
109+
- **Powertools for AWS Lambda on Discord**: `#typescript` - **[Invite link](https://discord.gg/B8zZKbbyET)**
110+
- **Email**: <[email protected]>
88111

89112
## How to support Powertools for AWS Lambda (TypeScript)?
90113

@@ -94,29 +117,25 @@ Knowing which companies are using this library is important to help prioritize t
94117

95118
The following companies, among others, use Powertools:
96119

97-
* [Hashnode](https://hashnode.com/)
98-
* [Trek10](https://www.trek10.com/)
99-
* [Elva](https://elva-group.com)
100-
* [globaldatanet](https://globaldatanet.com/)
101-
* [Bailey Nelson](https://www.baileynelson.com.au)
102-
* [Perfect Post](https://www.perfectpost.fr)
103-
* [Sennder](https://sennder.com/)
104-
* [Certible](https://www.certible.com/)
105-
* [tecRacer GmbH & Co. KG](https://www.tecracer.com/)
106-
* [AppYourself](https://appyourself.net)
107-
* [Alma Media](https://www.almamedia.fi)
120+
- [Hashnode](https://hashnode.com/)
121+
- [Trek10](https://www.trek10.com/)
122+
- [Elva](https://elva-group.com)
123+
- [globaldatanet](https://globaldatanet.com/)
124+
- [Bailey Nelson](https://www.baileynelson.com.au)
125+
- [Perfect Post](https://www.perfectpost.fr)
126+
- [Sennder](https://sennder.com/)
127+
- [Certible](https://www.certible.com/)
128+
- [tecRacer GmbH & Co. KG](https://www.tecracer.com/)
129+
- [AppYourself](https://appyourself.net)
130+
- [Alma Media](https://www.almamedia.fi)
108131

109132
### Sharing your work
110133

111134
Share what you did with Powertools for AWS Lambda (TypeScript) 💞💞. Blog post, workshops, presentation, sample apps and others. Check out what the community has already shared about Powertools for AWS Lambda (TypeScript) [here](https://docs.powertools.aws.dev/lambda/typescript/latest/we_made_this).
112135

113136
### Using Lambda Layer
114137

115-
This helps us understand who uses Powertools for AWS Lambda (TypeScript) in a non-intrusive way, and helps us gain future investments for other Powertools for AWS Lambda languages. When [using Layers](#lambda-layers), you can add Powertools for AWS Lambda (TypeScript) as a dev dependency (or as part of your virtual env) to not impact the development process.
116-
117-
## Credits
118-
119-
Credits for the Lambda Powertools for AWS Lambda (TypeScript) idea go to [DAZN](https://github.com/getndazn) and their [DAZN Lambda Powertools](https://github.com/getndazn/dazn-lambda-powertools/).
138+
This helps us understand who uses Powertools for AWS Lambda (TypeScript) in a non-intrusive way, and helps us gain future investments for other Powertools for AWS Lambda languages. When [using Layers](https://docs.powertools.aws.dev/lambda/typescript/latest/#lambda-layer), you can add Powertools as a dev dependency to not impact the development process.
120139

121140
## License
122141

packages/commons/src/Utility.ts

+39-13
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,11 @@
11
/**
2-
* ## Intro
3-
* Utility is a base class that other Powertools for AWS Lambda (TypeScript) utilites can extend to inherit shared logic.
2+
* `Utility` is a base class that other Powertools for AWS Lambda (TypeScript) utilites can extend to inherit shared logic.
43
*
4+
* Its main purpose is to encapsulate the cold start heuristic logic. Cold start is a term commonly used to describe the `Init` phase of a Lambda function.
5+
* In this phase, Lambda creates or unfreezes an execution environment with the configured resources, downloads the code for the function and all layers,
6+
* initializes any extensions, initializes the runtime, and then runs the function’s initialization code (the code outside the main handler).
57
*
6-
* ## Key features
7-
* * Cold Start heuristic to determine if the current
8-
*
9-
* ## Usage
10-
*
11-
* ### Cold Start
12-
*
13-
* Cold start is a term commonly used to describe the `Init` phase of a Lambda function. In this phase, Lambda creates or unfreezes an execution environment with the configured resources, downloads the code for the function and all layers, initializes any extensions, initializes the runtime, and then runs the function’s initialization code (the code outside the main handler). The Init phase happens either during the first invocation, or in advance of function invocations if you have enabled provisioned concurrency.
8+
* The Init phase happens either during the first invocation, or in advance of function invocations if you have enabled provisioned concurrency.
149
*
1510
* To learn more about the Lambda execution environment lifecycle, see the [Execution environment section](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-context.html) of the AWS Lambda documentation.
1611
*
@@ -21,7 +16,7 @@
2116
*
2217
* If you want to use this logic in your own utilities, `Utility` provides two methods:
2318
*
24-
* #### `getColdStart()`
19+
* `Utility.getColdStart()`
2520
*
2621
* Since the `Utility` class is instantiated outside of the Lambda handler it will persist across invocations of the same execution environment. This means that if you call `getColdStart()` multiple times, it will return `true` during the first invocation, and `false` afterwards.
2722
*
@@ -36,7 +31,7 @@
3631
* };
3732
* ```
3833
*
39-
* #### `isColdStart()`
34+
* `Utility.isColdStart()`
4035
*
4136
* This method is an alias of `getColdStart()` and is exposed for convenience and better readability in certain usages.
4237
*
@@ -59,6 +54,20 @@ export class Utility {
5954
private coldStart = true;
6055
private readonly defaultServiceName: string = 'service_undefined';
6156

57+
/**
58+
* Get the cold start status of the current execution environment.
59+
*
60+
* @example
61+
* ```typescript
62+
* import { Utility } from '@aws-lambda-powertools/commons';
63+
*
64+
* const utility = new Utility();
65+
* utility.isColdStart(); // true
66+
* utility.isColdStart(); // false
67+
* ```
68+
*
69+
* The method also flips the cold start status to `false` after the first invocation.
70+
*/
6271
public getColdStart(): boolean {
6372
if (this.coldStart) {
6473
this.coldStart = false;
@@ -69,10 +78,27 @@ export class Utility {
6978
return false;
7079
}
7180

81+
/**
82+
* Get the cold start status of the current execution environment.
83+
*
84+
* @example
85+
* ```typescript
86+
* import { Utility } from '@aws-lambda-powertools/commons';
87+
*
88+
* const utility = new Utility();
89+
* utility.isColdStart(); // true
90+
* utility.isColdStart(); // false
91+
* ```
92+
*
93+
* @see {@link getColdStart}
94+
*/
7295
public isColdStart(): boolean {
7396
return this.getColdStart();
7497
}
7598

99+
/**
100+
* Get the default service name.
101+
*/
76102
protected getDefaultServiceName(): string {
77103
return this.defaultServiceName;
78104
}
@@ -81,7 +107,7 @@ export class Utility {
81107
* Validate that the service name provided is valid.
82108
* Used internally during initialization.
83109
*
84-
* @param serviceName - Service name to validate
110+
* @param serviceName Service name to validate
85111
*/
86112
protected isValidServiceName(serviceName?: string): boolean {
87113
return typeof serviceName === 'string' && serviceName.trim().length > 0;

packages/commons/src/awsSdkUtils.ts

+26-7
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,6 @@
11
import { PT_VERSION } from './version.js';
22
import type { MiddlewareArgsLike, SdkClient } from './types/awsSdk.js';
33

4-
/**
5-
* @internal
6-
*/
74
const EXEC_ENV = process.env.AWS_EXECUTION_ENV || 'NA';
85
const middlewareOptions = {
96
relation: 'after',
@@ -13,8 +10,9 @@ const middlewareOptions = {
1310
};
1411

1512
/**
13+
* Type guard to check if the client provided is a valid AWS SDK v3 client.
14+
*
1615
* @internal
17-
* Type guard to check if the client provided is a valid AWS SDK v3 client
1816
*/
1917
const isSdkClient = (client: unknown): client is SdkClient =>
2018
typeof client === 'object' &&
@@ -35,9 +33,16 @@ const isSdkClient = (client: unknown): client is SdkClient =>
3533
typeof client.middlewareStack.addRelativeTo === 'function';
3634

3735
/**
36+
* Helper function to create a custom user agent middleware for the AWS SDK v3 clients.
37+
*
38+
* The middleware will append the provided feature name and the current version of
39+
* the Powertools for AWS Lambda library to the user agent string.
40+
*
41+
* @example "PT/Tracer/2.1.0 PTEnv/nodejs20x"
42+
*
43+
* @param feature The feature name to be added to the user agent
44+
*
3845
* @internal
39-
* returns a middleware function for the MiddlewareStack, that can be used for the SDK clients
40-
* @param feature
4146
*/
4247
const customUserAgentMiddleware = (feature: string) => {
4348
return <T extends MiddlewareArgsLike>(next: (arg0: T) => Promise<T>) =>
@@ -51,8 +56,12 @@ const customUserAgentMiddleware = (feature: string) => {
5156
};
5257

5358
/**
59+
* Check if the provided middleware stack already has the Powertools for AWS Lambda
60+
* user agent middleware.
61+
*
62+
* @param middlewareStack The middleware stack to check
63+
*
5464
* @internal
55-
* Checks if the middleware stack already has the Powertools UA middleware
5665
*/
5766
const hasPowertools = (middlewareStack: string[]): boolean => {
5867
let found = false;
@@ -65,6 +74,16 @@ const hasPowertools = (middlewareStack: string[]): boolean => {
6574
return found;
6675
};
6776

77+
/**
78+
* Add the Powertools for AWS Lambda user agent middleware to the
79+
* AWS SDK v3 client provided.
80+
*
81+
* We use this middleware to unbotrusively track the usage of the library
82+
* and secure continued investment in the project.
83+
*
84+
* @param client The AWS SDK v3 client to add the middleware to
85+
* @param feature The feature name to be added to the user agent
86+
*/
6887
const addUserAgentMiddleware = (client: unknown, feature: string): void => {
6988
try {
7089
if (isSdkClient(client)) {

0 commit comments

Comments
 (0)