2016-11-09 22:59:41 +00:00
|
|
|
'use strict'
|
|
|
|
|
|
|
|
const http = require('http')
|
2017-05-12 10:22:06 +00:00
|
|
|
const connect = require('connect')
|
2017-05-20 09:14:31 +00:00
|
|
|
const path = require('path')
|
2016-11-09 22:59:41 +00:00
|
|
|
|
|
|
|
class Server {
|
|
|
|
constructor (nuxt) {
|
2016-11-16 17:41:09 +00:00
|
|
|
this.nuxt = nuxt
|
2017-05-12 10:22:06 +00:00
|
|
|
// Initialize
|
|
|
|
this.app = connect()
|
|
|
|
this.server = http.createServer(this.app)
|
2017-05-19 07:35:20 +00:00
|
|
|
// Add Middleware
|
|
|
|
this.nuxt.options.serverMiddleware.forEach(m => {
|
2017-05-20 09:14:31 +00:00
|
|
|
this.useMiddleware(m)
|
2017-05-12 10:22:06 +00:00
|
|
|
})
|
|
|
|
// Add default render middleware
|
2017-05-20 09:14:31 +00:00
|
|
|
this.useMiddleware(this.render.bind(this))
|
2016-11-16 17:41:09 +00:00
|
|
|
return this
|
|
|
|
}
|
|
|
|
|
2017-05-20 09:14:31 +00:00
|
|
|
useMiddleware (m) {
|
|
|
|
// Require if needed
|
|
|
|
if (typeof m === 'string') {
|
|
|
|
let src = m
|
|
|
|
// Using ~ shorthand to resolve from project srcDir
|
|
|
|
if (src.indexOf('~') === 0) {
|
2017-05-21 15:41:00 +00:00
|
|
|
src = path.resolve(this.nuxt.options.srcDir, src.replace(/^~\/?/, ''))
|
2017-05-20 09:14:31 +00:00
|
|
|
}
|
|
|
|
// eslint-disable-next-line no-eval
|
|
|
|
m = eval('require')(src)
|
|
|
|
}
|
|
|
|
if (m instanceof Function) {
|
|
|
|
this.app.use(m)
|
|
|
|
} else if (m && m.path && m.handler) {
|
|
|
|
this.app.use(m.path, m.handler)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-05-12 10:22:06 +00:00
|
|
|
render (req, res, next) {
|
2016-11-16 17:41:09 +00:00
|
|
|
this.nuxt.render(req, res)
|
2016-11-09 22:59:41 +00:00
|
|
|
return this
|
|
|
|
}
|
|
|
|
|
|
|
|
listen (port, host) {
|
2017-03-25 14:16:07 +00:00
|
|
|
host = host || '127.0.0.1'
|
2016-11-09 22:59:41 +00:00
|
|
|
port = port || 3000
|
|
|
|
this.server.listen(port, host, () => {
|
2016-12-08 15:41:20 +00:00
|
|
|
console.log('Ready on http://%s:%s', host, port) // eslint-disable-line no-console
|
2016-11-09 22:59:41 +00:00
|
|
|
})
|
2016-11-16 17:41:09 +00:00
|
|
|
return this
|
2016-11-09 22:59:41 +00:00
|
|
|
}
|
|
|
|
|
2016-12-09 22:07:18 +00:00
|
|
|
close (cb) {
|
|
|
|
return this.server.close(cb)
|
|
|
|
}
|
2016-11-09 22:59:41 +00:00
|
|
|
}
|
|
|
|
|
2017-01-11 19:14:59 +00:00
|
|
|
export default Server
|