3

So I have Hapi (v17.5.1) and when I have my plugins array as

[
 {
  plugin: good,
  options: {
    reporters: {
      errorReporter: [
        {
          module: 'good-squeeze',
          name: 'Squeeze',
          args: [{ error: '*' }],
        }, {
          module: 'good-console',
        },
        'stderr',
      ],
      infoReporter: [
        {
          module: 'good-squeeze',
          name: 'Squeeze',
          args: [{ log: '*', response: '*' }],
        }, {
          module: 'good-console',
        },
        'stdout',
      ],
    },
  }
]

Let's save it in a variable goodPlugin for the next example.

That is, only with the good plugin and it works fine but when I go and try to add Inert, Vision or Hapi-Swagger, it breaks giving the error Cannot start server before plugins finished registration.

An example:

const HapiSwagger = require('hapi-swagger');
const Inert = require('inert');
const Vision = require('vision');
const Pack = require('../package');
module.exports = [
    Inert,
    Vision,
    // goodPlugin,
    {
        plugin: HapiSwagger,
        options: {
            info: {
              title: Pack.description,
              version: Pack.version,
            },
          },
        }
    ];

Where am I going wrong? I even tried to add this only when the development mode is on, but it gave me the same error.

halfer
  • 19,824
  • 17
  • 99
  • 186
Aakash Verma
  • 3,705
  • 5
  • 29
  • 66
  • In Hapi 17, the call to register plugins returns a promise, are you handling this correctly? – Ankh Jun 26 '18 at 07:13

1 Answers1

5

Do you use await when registering plugins? As suggested per documentation, the plugin registration part should look like this:

const init = async () => {

    await server.register({
        plugin: require('hapi-pino')
    });

    await server.start();
    console.log(`Server running at: ${server.info.uri}`);
};

init();
Eduard Avetisyan
  • 471
  • 1
  • 4
  • 20
  • Yes, this is the answer. Basically I was using the await for register function but this call to server.register was itself inside an async function which I was calling without await. Is it so that the function that's `async` has to have an `await` on calling it? – Aakash Verma Jun 28 '18 at 17:06
  • 1
    `async` functions are declared so that you can use `await` inside them. Async functions themselves do not need to be called with `await`. In this case, async function `init` allows using `await` inside it and with `await` we ensure that `server.register` is finished before `server.start` is called. – Eduard Avetisyan Jun 29 '18 at 07:36