Skip to content

Commit 56c24d2

Browse files
authored
docs: update readme re: middleware, deep imports (#5672)
1 parent ddc477c commit 56c24d2

File tree

1 file changed

+45
-15
lines changed

1 file changed

+45
-15
lines changed

README.md

Lines changed: 45 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -147,20 +147,26 @@ Some feedback we received frequently was that it can be difficult to debug what
147147
We’ve switched to using a middleware stack to control the lifecycle of an operation call now.
148148
This gives us a few benefits. Each middleware in the stack calls the next middleware after making any changes to the request object.
149149
This also makes debugging issues in the stack much easier since you can see exactly which middleware have been called leading up to an error.
150-
Here’s an example of adding a custom header using middleware:
150+
Here’s an example of logging requests using middleware:
151151

152152
```javascript
153153
const client = new DynamoDB({ region: "us-west-2" });
154+
154155
client.middlewareStack.add(
155156
(next, context) => (args) => {
156-
args.request.headers["Custom-Header"] = "value";
157-
console.log("\n -- printed from inside middleware -- \n");
158-
return next(args);
157+
console.log("AWS SDK context", context.clientName, context.commandName);
158+
console.log("AWS SDK request input", args.input);
159+
const result = await next(args);
160+
console.log("AWS SDK request output:", result.output);
161+
return result;
159162
},
160163
{
164+
name: "MyMiddleware",
161165
step: "build",
166+
override: true,
162167
}
163168
);
169+
164170
await client.listTables({});
165171
```
166172

@@ -176,28 +182,31 @@ we have them listed in [UPGRADING.md](https://github.com/aws/aws-sdk-js-v3/blob/
176182
## Working with the SDK in Lambda
177183

178184
### General Info
185+
179186
The Lambda provided AWS SDK is set to a specific minor version, and **NOT** the latest version. To check the minor version used by Lambda please refer to [Lambda runtimes doc page](https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html).
180187
If you wish to use the latest / different version of the SDK from the one provided by lambda, we recommend that you [bundle and minify](https://aws.amazon.com/blogs/compute/optimizing-node-js-dependencies-in-aws-lambda/) your project, or [upload it as a Lambda layer](https://aws.amazon.com/blogs/compute/using-lambda-layers-to-simplify-your-development-process/).
181188

182189
The performance of the AWS SDK for JavaScript v3 on node 18 has improved from v2 as seen in the [performance benchmarking](https://aws.amazon.com/blogs/developer/reduce-lambda-cold-start-times-migrate-to-aws-sdk-for-javascript-v3/)
183190

184191
### Best practices
192+
185193
When using Lambda we should use a single SDK client per service, per region, and initialize it outside of the handler's codepath. This is done to optimize for Lambda's [container reuse](https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtime-environment.html).
186194

187-
The API calls themselves should be made from within the handler's codepath.
195+
The API calls themselves should be made from within the handler's codepath.
188196
This is done to ensure that API calls are signed at the very last step of Lambda's execution cycle, after the Lambda is "hot" to avoid signing time skew.
189197

190198
Example:
199+
191200
```javascript
192201
import { STSClient, GetCallerIdentityCommand } from "@aws-sdk/client-sts";
193202

194203
const client = new STSClient({}); // SDK Client initialized outside the handler
195204

196205
export const handler = async (event) => {
197206
const response = {
198-
statusCode: 200,
207+
statusCode: 200,
199208
headers: {
200-
'Content-Type': 'application/json',
209+
"Content-Type": "application/json",
201210
},
202211
};
203212

@@ -207,9 +216,9 @@ export const handler = async (event) => {
207216
userId: results.UserId,
208217
};
209218

210-
response.body = JSON.stringify(responseBody);
219+
response.body = JSON.stringify(responseBody);
211220
} catch (err) {
212-
console.log('Error:', err);
221+
console.log("Error:", err);
213222
response.statusCode = 500;
214223
response.body = JSON.stringify({
215224
message: "Internal Server Error",
@@ -263,7 +272,7 @@ All clients have been published to NPM and can be installed as described above.
263272
```
264273
yarn add ./path/to/vendors/folder/aws-sdk-client-dynamodb-v3.0.0.tgz
265274
```
266-
275+
267276
## Giving feedback and contributing
268277

269278
You can provide feedback to us in several ways. Both positive and negative feedback is appreciated.
@@ -510,29 +519,33 @@ For a full abort controller deep dive please check out our [blog post](https://a
510519

511520
### Middleware Stack
512521

513-
The JavaScript SDK maintains a series of asynchronous actions. These series include actions that serialize input parameters into the data over the wire and deserialize response data into JavaScript objects. Such actions are implemented using functions called middleware and executed in a specific order. The object that hosts all the middleware including the ordering information is called a Middleware Stack. You can add your custom actions to the SDK and/or remove the default ones.
522+
The AWS SDK for JavaScript (v3) maintains a series of asynchronous actions. These series include actions that serialize input parameters into the data over the wire and deserialize response data into JavaScript objects. Such actions are implemented using functions called middleware and executed in a specific order. The object that hosts all the middleware including the ordering information is called a Middleware Stack. You can add your custom actions to the SDK and/or remove the default ones.
514523

515524
When an API call is made, SDK sorts the middleware according to the step it belongs to and its priority within each step. The input parameters pass through each middleware. An HTTP request gets created and updated along the process. The HTTP Handler sends a request to the service, and receives a response. A response object is passed back through the same middleware stack in reverse, and is deserialized into a JavaScript object.
516525

517526
A middleware is a higher-order function that transfers user input and/or HTTP request, then delegates to “next” middleware. It also transfers the result from “next” middleware. A middleware function also has access to context parameter, which optionally contains data to be shared across middleware.
518527

519-
For example, you can use middleware to add a custom header like S3 object metadata:
528+
For example, you can use middleware to log or modify a request:
520529

521530
```javascript
522531
const { S3 } = require("@aws-sdk/client-s3");
523532
const client = new S3({ region: "us-west-2" });
533+
524534
// Middleware added to client, applies to all commands.
525535
client.middlewareStack.add(
526-
(next, context) => async (args) => {
536+
(next, context) => (args) => {
527537
args.request.headers["x-amz-meta-foo"] = "bar";
538+
console.log("AWS SDK context", context.clientName, context.commandName);
539+
console.log("AWS SDK request input", args.input);
528540
const result = await next(args);
529-
// result.response contains data returned from next middleware.
541+
console.log("AWS SDK request output:", result.output);
530542
return result;
531543
},
532544
{
533545
step: "build",
534546
name: "addFooMetadataMiddleware",
535547
tags: ["METADATA", "FOO"],
548+
override: true,
536549
}
537550
);
538551

@@ -551,8 +564,10 @@ The example above adds middleware to `build` step of middleware stack. The middl
551564

552565
```javascript
553566
client.middlewareStack.add(middleware, {
567+
name: "MyMiddleware",
554568
step: "initialize",
555569
priority: "high", // or "low".
570+
override: true, // provide both a name and override=true to avoid accidental middleware duplication.
556571
});
557572
```
558573

@@ -582,15 +597,30 @@ Earlier versions require Node.js >= 10.
582597
| @aws-sdk/middleware-stack | packages | AWS SDK JS team | public/stable |
583598
| remaining @aws-sdk/\* | packages | AWS SDK JS team | internal |
584599

600+
Public interfaces are marked with the `@public` annotation in source code and appear
601+
in our [API Reference](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/).
602+
585603
Additional notes:
586604

587-
- internal does not mean a package or interface is constantly changing
605+
- `@internal` does not mean a package or interface is constantly changing
588606
or being actively worked on. It means it is subject to change without any
589607
notice period. The changes are included in the release notes.
590608
- public interfaces such as client configuration are also subject to change
591609
in exceptional cases. We will try to undergo a deprecation period with
592610
an advance notice.
593611

612+
All supported interfaces are provided at the package level, e.g.:
613+
614+
```js
615+
import { S3Client } from "@aws-sdk/client-s3"; // Yes, do this.
616+
617+
import { S3Client } from "@aws-sdk/client-s3/dist-cjs/S3Client"; // No, don't do this.
618+
```
619+
620+
Do not import from a deep path in any package, since the file structure may change, and
621+
in the future packages may include the `exports` metadata in `package.json` preventing
622+
access to the file structure.
623+
594624
## Known Issues
595625

596626
### Functionality requiring AWS Common Runtime (CRT)

0 commit comments

Comments
 (0)