Generator function to be used as middlewares in express like koa. ( use lei-coroutine )
npm install express-coroutine --save
const express = require('express-coroutine')(require('express')); const app = express();
const express = require('express-coroutine')(require('express')); const app = express(); const router = new expressGenerators.Router(); app.use(router); router.get('/', 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!'); }); 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); }; app.get('/:user', middleware, function* (req, res) { res.send('it works!'); });
More detail demo can be found in test.js