async-ware

A class for easily writing js middlewares

Usage no npm install needed!

<script type="module">
  import asyncWare from 'https://cdn.skypack.dev/async-ware';
</script>

README

async-ware

NPM version Build status Test coverage License

The programming idea(🧅 onion model) of koa middleware is great, it can be applied to more situations.

We need one class to include that all, so here comes this lib

  • ✅ use it in one class(no need to include koa), see code example below
  • ✅ variadic arguments for the whole running
  • ✅ catch the error by ware.run() 's promise

How to use

Install

npm i async-ware -S

Example

const Middleware = require('async-ware')

const ware = new Middleware()

ware.use(async (a, b, next) => {
  console.log('middleware 1a ***', ++a.a, a)
  await next()
  console.log('middleware 1b ***', ++b.b, b)
})

ware.use(async (a, b, next) => {
  console.log('middleware 2a ***', ++a.a, a)
  await sleep(200)
  await next()
  await sleep(300)
  console.log('middleware 2b ***', ++b.b, b)
})

ware.use(async (a, b, next) => {
  console.log('middleware 3a ***', ++a.a, a)
  await sleep(400)
  await next()
  await sleep(500)
  console.log('middleware 3b ***', ++b.b, b)
})

// The middlewares above, function's arguments a and b is the `run` function's arguments
// You can use variadic arguments here
ware.run({ a: 10 }, { b: 20 })
  .then(console.log)
  .catch(console.error)

License

MIT