Router middleware for Midly
let router = require('midly-router')()
.get('/test/route', (req, res, ctx) => {
res.body = 'test route'
return true
})
.all('/test/:param', (req, res, ctx) => {
res.body = req.params
})
require('midly')()
.use(router)
.listen(3000)
console.log('Midly started on port 3000')
Installation
From npm registry:
$ npm install midly-router
API
Methods
Router([prefix])
Create a new router
The prefix will be added before all string paths
router.use(...middlewares)
Add the given middleware functions to this router
router.get|post|put|patch|delete|all(paths, ...callbacks)
Routes HTTP requests to the specified path or array of paths with the specified callback functions
router
.all('/user/:id', async (req, res, ctx) => {
ctx.user = await db.get.user({id: req.params.id})
if(ctx.user) return true
})
.get('/user/:id', (req, res, ctx) => {
res.body = `Hello ${ctx.user.name}!`
})
.post('/user/:id', (req, res, ctx) => {
res.body = 'Welcome to Legion, ' + ctx.user.name
})
.put('/user/:id', (req, res, ctx) => {
res.body = 'Information has been updated'
})
.delete('/users/:id', (req, res, ctx) => {
db.delete.user({id: req.params.id})
res.body = 'Your account has been deleted'
})
Route paths will be translated to regular expressions using path2regexp
Query strings will not be considered when matching requests
Multiple middleware may be given:
router.get('/users/:id',
async (req, res, ctx) => {
ctx.user = await User.findOne(req.params.id)
return true
},
(req, res, ctx) => {
console.log(ctx.user)
})
router.redirect(paths, url, [code])
Perform a redirect to url
Events
error
- Midly router wiil emit this event when an error occurs in middleware