fix: require serverMiddleware object with path and handler (#4656)

This commit is contained in:
Alexander Lichter 2018-12-29 22:34:47 +01:00 committed by Pooya Parsa
parent c4b5b51fbe
commit 8786ff7317
4 changed files with 27 additions and 2 deletions

View File

@ -176,7 +176,17 @@ export default class Server {
// Resolve handler setup as string (path)
if (typeof handler === 'string') {
try {
handler = this.nuxt.resolver.requireModule(middleware.handler || middleware)
const requiredModuleFromHandlerPath = this.nuxt.resolver.requireModule(handler)
// In case the "handler" is not derived from an object but is a normal string, another object with
// path and handler could be the result
// If the required module has handler, treat the module as new "middleware" object
if (requiredModuleFromHandlerPath.handler) {
middleware = requiredModuleFromHandlerPath
}
handler = requiredModuleFromHandlerPath.handler || requiredModuleFromHandlerPath
} catch (err) {
if (!this.options.dev) {
throw err[0]

View File

@ -0,0 +1,7 @@
export default {
path: '/midd3',
handler(req, res) {
res.write('Be creative when writing test strings! Hey Mama :wave:')
res.end()
}
}

View File

@ -12,7 +12,10 @@ export default {
},
['./modules/template', { baz: 'ping' }]
],
serverMiddleware: ['./modules/middleware/midd2'],
serverMiddleware: [
'./modules/middleware/midd2',
'~/modules/middleware/midd3'
],
hooks(hook) {
hook('ready', (nuxt) => {
nuxt.__ready_called__ = true

View File

@ -54,6 +54,11 @@ describe('module', () => {
expect(response).toBe('It works!')
})
test('serverMiddleware with path', async () => {
const response = await rp(url('/midd3'))
expect(response).toBe('Be creative when writing test strings! Hey Mama :wave:')
})
test('Hooks - Use external middleware before render', async () => {
const response = await rp(url('/use-middleware'))
expect(response).toBe('Use external middleware')