🔥 Server Middlewares

This commit adds `middlewares` option to nuxt and accepts connect style middlewares.
Also modules can register middlewares using `this.addMiddleware()` method.
Each entry can be a simple middleware function or {path, handler} to support paths.
This commit is contained in:
Pooya Parsa 2017-05-12 14:52:06 +04:30
parent d98c24b9b9
commit 9c1060e06c
5 changed files with 6387 additions and 2 deletions

View File

@ -59,6 +59,10 @@ class Module {
}) })
} }
addMiddleware (middleware) {
this.options.middlewares.push(middleware)
}
extendBuild (fn) { extendBuild (fn) {
this.options.build.extend = chainFn(this.options.build.extend, fn) this.options.build.extend = chainFn(this.options.build.extend, fn)
} }

View File

@ -28,6 +28,7 @@ class Nuxt {
plugins: [], plugins: [],
css: [], css: [],
modules: [], modules: [],
middlewares: [],
cache: false, cache: false,
loading: { loading: {
color: 'black', color: 'black',

View File

@ -1,15 +1,28 @@
'use strict' 'use strict'
const http = require('http') const http = require('http')
const connect = require('connect')
class Server { class Server {
constructor (nuxt) { constructor (nuxt) {
this.nuxt = nuxt this.nuxt = nuxt
this.server = http.createServer(this.render.bind(this)) // Initialize
this.app = connect()
this.server = http.createServer(this.app)
// Add Middlewares
this.nuxt.options.middlewares.forEach(m => {
if (m instanceof Function) {
this.app.use(m)
} else if (m && m.path && m.handler) {
this.app.use(m.path, m.handler)
}
})
// Add default render middleware
this.app.use(this.render.bind(this))
return this return this
} }
render (req, res) { render (req, res, next) {
this.nuxt.render(req, res) this.nuxt.render(req, res)
return this return this
} }

View File

@ -60,6 +60,7 @@
"chokidar": "^1.6.1", "chokidar": "^1.6.1",
"co": "^4.6.0", "co": "^4.6.0",
"compression": "^1.6.2", "compression": "^1.6.2",
"connect": "^3.6.1",
"css-loader": "^0.28.1", "css-loader": "^0.28.1",
"debug": "^2.6.6", "debug": "^2.6.6",
"extract-text-webpack-plugin": "^2.1.0", "extract-text-webpack-plugin": "^2.1.0",

6366
yarn.lock Executable file

File diff suppressed because it is too large Load Diff