From 7137f848a295c95a0d41e9d0e7ed150d77ce6b24 Mon Sep 17 00:00:00 2001 From: Atinux Date: Tue, 31 Oct 2017 12:33:15 +0100 Subject: [PATCH] hooks: Handle hooks as object --- lib/common/options.js | 2 +- lib/core/nuxt.js | 21 +++++++++++++++++++-- test/basic.generate.test.js | 4 ++++ test/fixtures/basic/nuxt.config.js | 7 +++++++ 4 files changed, 31 insertions(+), 3 deletions(-) diff --git a/lib/common/options.js b/lib/common/options.js index fc31e04878..3aea5e59ae 100755 --- a/lib/common/options.js +++ b/lib/common/options.js @@ -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', diff --git a/lib/core/nuxt.js b/lib/core/nuxt.js index 7bc22fac2e..e418db59c4 100644 --- a/lib/core/nuxt.js +++ b/lib/core/nuxt.js @@ -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:') @@ -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 @@ -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) } @@ -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) => { diff --git a/test/basic.generate.test.js b/test/basic.generate.test.js index 313203637a..dc0eb55caf 100644 --- a/test/basic.generate.test.js +++ b/test/basic.generate.test.js @@ -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 diff --git a/test/fixtures/basic/nuxt.config.js b/test/fixtures/basic/nuxt.config.js index fb6e6734c7..ace0d54b37 100644 --- a/test/fixtures/basic/nuxt.config.js +++ b/test/fixtures/basic/nuxt.config.js @@ -6,5 +6,12 @@ module.exports = { { route: '/users/3', payload: { id: 3000 } } ], interval: 200 + }, + hooks: { + ready(nuxt) { + nuxt.__hook_called__ = true + }, + bad: null, + '': true } }