Skip to content

Generator function and Async function to be used as middlewares in express like koa.

License

Notifications You must be signed in to change notification settings

yourtion/express-coroutine

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

64 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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;