Use serverMiddleware instead of a module

This commit is contained in:
Sébastien Chopin 2017-07-08 18:09:47 +02:00
parent 1f7508d033
commit 1d77431db0
2 changed files with 34 additions and 38 deletions

View File

@ -1,38 +1,36 @@
const express = require('express')
module.exports = function () {
// Create express router
const router = express.Router()
// Create express router
const router = express.Router()
var app = express()
// Transform req & res to have the same API as express
// So we can use res.status() & res.json()
router.use((req, res, next) => {
// Transform req & res to have the same API as express
// So we can use res.status() & res.json()
var app = express()
router.use((req, res, next) => {
Object.setPrototypeOf(req, app.request)
Object.setPrototypeOf(res, app.response)
req.res = res
res.req = req
next()
})
})
// Add POST - /api/login
router.post('/login', (req, res) => {
// Add POST - /api/login
router.post('/login', (req, res) => {
if (req.body.username === 'demo' && req.body.password === 'demo') {
req.session.authUser = { username: 'demo' }
return res.json({ username: 'demo' })
}
res.status(401).json({ message: 'Bad credentials' })
})
})
// Add POST - /api/logout
router.post('/logout', (req, res) => {
// Add POST - /api/logout
router.post('/logout', (req, res) => {
delete req.session.authUser
res.json({ ok: true })
})
})
// Add router to /api
this.addServerMiddleware({
// Export the server middleware
module.exports = {
path: '/api',
handler: router
})
}

View File

@ -27,11 +27,9 @@ module.exports = {
resave: false,
saveUninitialized: false,
cookie: { maxAge: 60000 }
})
],
/*
** Add our custom module
** In this module we add /api/login & /api/logout routes
*/
modules: ['~/api']
}),
// Api middleware
// We add /api/login & /api/logout routes
'~/api'
]
}