Skip to content

Commit

Permalink
hooks: Handle hooks as object
Browse files Browse the repository at this point in the history
  • Loading branch information
Atinux committed Oct 31, 2017
1 parent 7aa0863 commit 7137f84
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 3 deletions.
2 changes: 1 addition & 1 deletion lib/common/options.js
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ Options.defaults = {
editor: {
editor: 'code'
},
hooks: () => {},
hooks: null,
messages: {
error_404: 'This page could not be found',
server_error: 'Server error',
Expand Down
21 changes: 19 additions & 2 deletions lib/core/nuxt.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import Renderer from './renderer'
import Debug from 'debug'
import enableDestroy from 'server-destroy'
import Module from 'module'
import { isPlainObject } from 'lodash'
import { join, resolve } from 'path'

const debug = Debug('nuxt:')
Expand Down Expand Up @@ -41,8 +42,10 @@ export default class Nuxt {
return this._ready
}

// Call hooks
if (typeof this.options.hooks === 'function') {
// Add hooks
if (isPlainObject(this.options.hooks)) {
this.addObjectHooks(this.options.hooks)
} else if (typeof this.options.hooks === 'function') {
this.options.hooks(this.hook)
}
// Add nuxt modules
Expand All @@ -56,6 +59,9 @@ export default class Nuxt {
}

hook(name, fn) {
if (!name || typeof fn !== 'function') {
return
}
this._hooks[name] = this._hooks[name] || []
this._hooks[name].push(fn)
}
Expand All @@ -73,6 +79,17 @@ export default class Nuxt {
}
}

addObjectHooks(hooksObj) {
Object.keys(hooksObj).forEach((name) => {
let hooks = hooksObj[name]
hooks = (Array.isArray(hooks) ? hooks : [hooks])

hooks.forEach((hook) => {
this.hook(name, hook)
})
})
}

listen(port = 3000, host = 'localhost') {
return new Promise((resolve, reject) => {
const server = this.renderer.app.listen({ port, host, exclusive: false }, (err) => {
Expand Down
4 changes: 4 additions & 0 deletions test/basic.generate.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ test.before('Init Nuxt.js', async t => {
server.listen(port)
})

test('Check ready hook called', async t => {
t.true(nuxt.__hook_called__)
})

test('/stateless', async t => {
const window = await nuxt.renderAndGetWindow(url('/stateless'))
const html = window.document.body.innerHTML
Expand Down
7 changes: 7 additions & 0 deletions test/fixtures/basic/nuxt.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,12 @@ module.exports = {
{ route: '/users/3', payload: { id: 3000 } }
],
interval: 200
},
hooks: {
ready(nuxt) {
nuxt.__hook_called__ = true
},
bad: null,
'': true
}
}

0 comments on commit 7137f84

Please sign in to comment.