Socket
Socket
Sign inDemoInstall

middy

Package Overview
Dependencies
Maintainers
8
Versions
147
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

middy - npm Package Compare versions

Comparing version 0.12.0 to 0.12.1

2

package.json
{
"name": "middy",
"version": "0.12.0",
"version": "0.12.1",
"description": "🛵 The stylish Node.js middleware engine for AWS Lambda",

@@ -5,0 +5,0 @@ "main": "./index.js",

@@ -57,4 +57,4 @@ <div align="center">

But code is better than 10.000 words, so let's jump into an example.
Let's assume you are building an JSON API to process a payment:
But code is better than 10,000 words, so let's jump into an example.
Let's assume you are building a JSON API to process a payment:

@@ -67,3 +67,3 @@ ```javascript

// This is your common handler, no way different than what you are used to do every day
// This is your common handler, in no way different than what you are used to doing every day
// in AWS Lambda

@@ -80,3 +80,4 @@ const processPayment = (event, context, callback) => {

// Notice that in the handler you only added base business logic (no deserilization, validation or error handler), we will add the rest with middlewares
// Notice that in the handler you only added base business logic (no deserilization,
// validation or error handler), we will add the rest with middlewares

@@ -118,3 +119,8 @@ const inputSchema = {

or
```bash
yarn add middy
```
## Requirements

@@ -133,3 +139,3 @@

Anyway, when you are writing an handler, you still have to deal with some common technical concerns
Anyway, when you are writing a handler, you still have to deal with some common technical concerns
outside business logic, like input parsing and validation, output serialization,

@@ -145,3 +151,3 @@ error handling, etc.

This pattern allows developers to isolate this common technical concerns into
This pattern allows developers to isolate these common technical concerns into
*"steps"* that *decorate* the main business logic code.

@@ -165,3 +171,3 @@ Middleware functions are generally written as independent modules and then plugged in into

2. Import `middy` and all the middlewares you want to use
3. Wrap you handler in the `middy()` factory function. This will return a new
3. Wrap your handler in the `middy()` factory function. This will return a new
enhanced instance of your original handler, to which you will be able to attach

@@ -192,3 +198,4 @@ the middlewares you need.

For a more detailed use cases and examples check the [Writing a middleware section](#writing-a-middleware) and the [API section](#api).
For a more detailed use case and examples check the [Writing a middleware section](#writing-a-middleware) and
the [API section](#api).

@@ -210,3 +217,3 @@

This way the *request-response cycle* flows through all the middlewares, the
handler and all the middlewares again, giving to every step, the opportunity to
handler and all the middlewares again, giving the opportunity within every step to
modify or enrich the current request, context or the response.

@@ -249,4 +256,4 @@

**Note**: this will totally stop the execution of successive middlewares in any phase (`before` and `after`) and returns
and early response (or an error) directly at the lambda level. If you middlewares that do specific task on every requests
like output serialization or error handling, those won't be invoked in this case.
an early response (or an error) directly at the Lambda level. If your middlewares do a specific task on every request
like output serialization or error handling, these won't be invoked in this case.

@@ -282,3 +289,3 @@ In this example we can use this capability for building a sample caching middleware:

// sample Usage
// sample usage
const handler = middy((event, context, callback) => { /* ... */ })

@@ -293,3 +300,3 @@ .use(cacheMiddleware({

But what happens in case there is an error?
But what happens when there is an error?

@@ -308,30 +315,14 @@ When there is an error, the regular control flow is stopped and the execution is

If no middleware manages the error, the lambda execution fails reporting the unmanaged error.
If no middleware manages the error, the Lambda execution fails reporting the unmanaged error.
### Promise support
### Async/Await support
Middy allows you to return promises (or throw errors) from your handlers (instead of calling `callback()`) and middlewares
(instead of calling `next()`).
Middy allows you to write *async/await handlers*. In *async/await handlers* you don't
have to invoke the callback but just return the output (in case of success) or
throw an error (in case of failure).
Here is an example of a handler that returns a promise:
We believe that this feature makes handling asynchronous logic easier to reason about
and asynchronous code easier to read.
Take the following code as an example:
```javascript
middy(async (event, context) => {
await someAsyncStuff()
await someOtherAsyncStuff()
return ({foo: bar})
})
```
this code is equivalent to:
```javascript
middy(async (event, context, callback) => {
someAsyncStuff()
middy((event, context, callback) => {
return someAsyncStuff()
.then(() => {

@@ -341,14 +332,9 @@ return someOtherAsyncStuff()

.then(() => {
callback(null, {foo: bar})
})
return {foo: bar}
}
})
```
Of course, since AWS lambda runs on Node.js 6.10, you will need to transpile your `async/await` code (e.g. using [babel](https://babeljs.io/)).
And here is an example of a middleware that returns a similar promise:
### Async Middlewares
Middy supports middlewares that return promises instead that directly calling the callback:
```javascript

@@ -358,5 +344,6 @@ const asyncValidator = () => {

if (handler.event.body) {
return new Promise((resolve, reject) => {
// async validation logic
})
return someAsyncStuff(handler.event.body)
.then(() => {
return {foo: bar}
})
}

@@ -371,9 +358,33 @@

Thanks to this behavior you can define middlewares using `async` functions:
### Using async/await
Node.js 8.10 supports [async/await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function),
allowing you to work with promises in a way that makes handling asynchronous logic easier to reason about and
asynchronous code easier to read.
You can still use async/await if you're running AWS Lambda on Node.js 6.10, but you will need to transpile your
`async/await` code (e.g. using [babel](https://babeljs.io/)).
Take the following code as an example of a handler written with async/await:
```javascript
middy(async (event, context) => {
await someAsyncStuff()
await someOtherAsyncStuff()
return ({foo: bar})
})
```
And here is an example of a middleware written with async/await:
```javascript
const asyncValidator = () => {
before: async (handler) => {
if (handler.event.body) {
return await asyncValidate(handler.event.body)
await asyncValidate(handler.event.body)
return {foo: bar}
}

@@ -388,5 +399,3 @@

Of course, since AWS lambda runs on Node.js 6.10, you will need to transpile your `async/await` code (e.g. using [babel](https://babeljs.io/)).
## Writing a middleware

@@ -410,6 +419,6 @@

- `handler`: is a reference to the current context and it allows to access (and modify)
- `handler`: is a reference to the current context and it allows access to (and modification of)
the current `event` (request), the `response` (in the *after* phase) and `error`
(in case of an error).
- `next`: is a callback function that needs to be invoked when the middleware finished
- `next`: is a callback function that needs to be invoked when the middleware has finished
its job so that the next middleware can be invoked

@@ -467,7 +476,7 @@

Sometimes you want to create handlers that serve very small needs and that are not
Sometimes you want to create handlers that serve a very small need and that are not
necessarily re-usable. In such cases you probably will need to hook only into one of
the different phases (`before`, `after` or `onError`).
In these cases you can use **inline middlewares** which are shortcut function to hook
In these cases you can use **inline middlewares** which are shortcut functions to hook
logic into Middy's control flow.

@@ -502,3 +511,3 @@

As you can see above, a middy instance exposes also the `before`, `after` and `onError`
As you can see above, a middy instance also exposes the `before`, `after` and `onError`
methods to allow you to quickly hook-in simple inline middlewares.

@@ -509,3 +518,3 @@

Check the [code for existing middlewares](/src/middlewares) to have more examples
Check the [code for existing middlewares](/src/middlewares) to see more examples
on how to write a middleware.

@@ -527,3 +536,3 @@

- [`jsonBodyParser`](/docs/middlewares.md#jsonbodyparser): Automatically parses HTTP requests with JSON body and converts the body into an object. Also handles gracefully broken JSON if used in combination of
`httpErrorHanler`.
`httpErrorHandler`.
- [`s3KeyNormalizer`](/docs/middlewares.md#s3keynormalizer): Normalizes key names in s3 events.

@@ -536,3 +545,3 @@ - [`ssm`](/docs/middlewares.md#ssm): Fetches parameters from [AWS Systems Manager Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-paramstore.html).

For a dedicated documentation on those middlewares check out the [Middlewares
For dedicated documentation on available middlewares check out the [Middlewares
documentation](/docs/middlewares.md)

@@ -539,0 +548,0 @@

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc