Universal Middleware
Fast, lightweight middleware framework.
Features
- Lightweight - less than 370 bytes minified
- Browser and Node - Use in browser and node
- Async Await and Promise support - Support both async await and promise functions
- No Dependency - No Bloating. No external dependencies
- Express.js style middlware - Express.js like design
Install
$ npm install umid
$ yarn add umid
Usage
Basic Example
const Middleware = ; const sleep = ; let m = ; // Plain middlewarem // Async await middleware; // Async await middlewarelet m3 = async { await ; await ; console; contextexec = "M3 executed in 1 second"; ;}; // settimeout middlewarelet { ;}; // Promise middlewarelet m5 = async { Promise;}; // Error middlewarelet errorMiddleware = async { throw "got error!!"; ;}; m; // m.use(errorMiddleware) async { let context = {}; let result = await m; console;};
or
let context = {};m;
Error Middleware example
const Middleware = ; let m = ; // Pass string in next to create an errorm // Throw an error // Throw error string // throw error in next function async { let context = {}; try let result = await m; console; catch error console; };
API
Middleware()
Returns an instance of a middleware
use((context, next))
Attach middleware(s).
These are the different signatures for use function
use(...middlewares)
use(middleware)
use([middleware1, middleware2])
use(middleware1, middleware2)
use(middleware1, [middleware2, middleware3], middlware4)
middleware
This is the signature for defining middleware.
(context, next)
context
The context that passes to the next middleware. This can be updated and passed on to next middleware.
next
Type: Function
Most importantly, a middleware must either call next() or terminate the response with next('reason').
run(initialContext)
Type: async Function. Returns updated context
initialContext
This is for assigning the middlewares with intial context object to pass.
process((err, context), initialContext)
(err, context)
Type: Function
Its signature is (err, context), where err is the String or Error thrown by the middleware.
initialContext
This is for assigning the middlewares with intial context object to pass.
Middleware Errors
If an error arises within a middleware, the loop will be exited. This means that no other middleware will execute.
There are three ways to "throw" an error from within a middleware function.
- Pass any string to next('Err')
This will exit the loop with your error string as the error message.
;
- Pass an Error to next()
This is similar to the above option.
;
- Terminate with throw
;
License
MIT © Kethan Surana