Generator function and Async function to be used as middlewares in express like koa.
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
.coveralls.yml
.eslintrc.js
.gitignore
.travis.yml
LICENSE
README.md
index.js
package.json
test.js

README.md

NPM version build status Test coverage David deps node version npm download npm license Greenkeeper badge

express-coroutine

Generator function and Async function to be used as middlewares in express like koa. ( use lei-coroutine )

Installation

npm install express-coroutine --save

Usage

Init express

const express = require('express-coroutine')(require('express'));
const app = express();

Init router

const express = require('express-coroutine')(require('express'));
const app = express();
const router = new express.Router();
app.use(router);

router.get('/', function* (req, res) {
  res.send('it works!');
});

// also async function
router.get('/', async function (req, res) {
  res.send('it works!');
});

Write your express routes by using generator functions as middlewares.

const express = require('express-coroutine')(require('express'));

const app = express();

app.get('/user/:id', function* (req, res) {
  const user = yield User.findById(req.params.id);
  res.send(user);
})

app.get('/error', function* (req, res) {
  throw new Error('Bang!');
});

// also async function
app.get('/user2/:id', async function* (req, res) {
  const user = await User.findById(req.params.id);
  res.send(user);
});

app.listen(8000);

You can also define multiple generator functions just the express way.

const fn = function (req, res, next) {
  return new Promise((resolve, reject) => {
    if (req.params.user !== 'a') return reject(new Error('Bang!'));
    resolve('a');
  });
};

const middleware = function* (req, res, next) {
  yield fn(req, res, next);
};

const middleware2 = async function (req, res, next) {
  await fn(req, res, next);
  next();
};

app.get('/:user', middleware, function* (req, res) {
  res.send('it works!');
});

app.get('/:user', middleware2, async function (req, res) {
  res.send('it works!');
});

More detail demo can be found in test.js

Get coroutine

const coroutine = require('express-coroutine').coroutine;