co-router
v1.1.0
Published
Benefit from generator on express router.
Downloads
525
Maintainers
Readme
co-router
Benefit from async/await or generators with express router.
Installation
$ npm install --save co-router
Usage
var Router = require('co-router');
var router = Router();
// Default Express.js route handler
router.get('/foo', function (req, res, next) {
var rows = db.query('SELECT 1 + 1', function (err, rows) {
if (err) {
return next(err);
}
return res.send(rows);
});
});
// Use an async function as route handler
router.get('/tom', async function (req, res, next) {
var rows = await db.query('SELECT 1 + 1');
// Uncaught error (reject) is handled with `next(err)`.
return res.send(rows);
});
// Use a generator function as route handler
router.get('/bar', function* (req, res, next) {
var rows = yield db.query('SELECT 1 + 1');
// Uncaught error (reject) is handled with `next(err)`.
return res.send(rows);
});
// Compatible with legacy route handler, helpful to reuse express middlewares
router.post('/baz', function (req, res, next) {
if (req.session.authenticated) {
return next();
} else {
return res.redirect(301, '/login.html');
}
}, function* (req, res, next) {
return res.send(yield Promise.resolve("Hello world"));
});
// Chaining routes
router.route('/baz')
.get(function* (req, res, next) {
// Do something...
})
.put(function* (req, res, next) {
// Do something...
});
// Generator in middleware
router.use(function* (req, res, next) {
// Do something
});
// And error handler
router.use(function* (err, req, res, next) {
// Handle error
});
License
(The MIT License)