improve serverMiddleware

This allows resolve using ~ path nation
This commit is contained in:
Pooya Parsa 2017-05-20 13:44:31 +04:30
parent f0c66b490a
commit aca45a15b0

View File

@ -2,6 +2,7 @@
const http = require('http') const http = require('http')
const connect = require('connect') const connect = require('connect')
const path = require('path')
class Server { class Server {
constructor (nuxt) { constructor (nuxt) {
@ -11,15 +12,29 @@ class Server {
this.server = http.createServer(this.app) this.server = http.createServer(this.app)
// Add Middleware // Add Middleware
this.nuxt.options.serverMiddleware.forEach(m => { this.nuxt.options.serverMiddleware.forEach(m => {
this.useMiddleware(m)
})
// Add default render middleware
this.useMiddleware(this.render.bind(this))
return this
}
useMiddleware (m) {
// Require if needed
if (typeof m === 'string') {
let src = m
// Using ~ shorthand to resolve from project srcDir
if (src.indexOf('~') === 0) {
src = path.resolve(this.nuxt.options.srcDir, src.substr(1))
}
// eslint-disable-next-line no-eval
m = eval('require')(src)
}
if (m instanceof Function) { if (m instanceof Function) {
this.app.use(m) this.app.use(m)
} else if (m && m.path && m.handler) { } else if (m && m.path && m.handler) {
this.app.use(m.path, m.handler) this.app.use(m.path, m.handler)
} }
})
// Add default render middleware
this.app.use(this.render.bind(this))
return this
} }
render (req, res, next) { render (req, res, next) {