How to use @hapi/hoek - 10 common examples

To help you get started, we’ve selected a few @hapi/hoek examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github futurestudio / hapi-pulse / test / server-stop-with-signals.js View on Github external
const server = new Hapi.Server()
    await server.register({
      plugin: require('../lib'),
      options: {
        signals: 'HAPIPULSE'
      }
    })

    await server.start()
    // a stopped hapi server has a "started" timestamp of 0
    expect(server.info.started).to.not.equal(0)

    process.emit('HAPIPULSE')

    // wait for the server to stop
    await Hoek.wait(100)

    Sinon.assert.called(process.exit)

    // a stopped hapi server has a "started" timestamp of 0
    expect(server.info.started).to.equal(0)
  })
})
github hapijs / nes / test / listener.js View on Github external
}
            };

            let d = 0;
            client.onDisconnect = (willReconnect, log) => ++d;

            await client.connect();
            expect(client._heartbeatTimeout).to.equal(380);

            await client.request('/');
            await Hoek.wait(520);

            expect(d).to.equal(0);

            client._onMessage = Hoek.ignore;            // Stop processing messages
            await Hoek.wait(480);

            expect(d).to.equal(1);

            client.disconnect();
            await server.stop();
        });
    });
github hapijs / catbox / test / policy.js View on Github external
const orig = client.connection.get;
                client.connection.get = async function (key) {      // Delayed get

                    await Hoek.wait(100);
                    return orig.call(client.connection, key);
                };

                const policy = new Catbox.Policy(rule, client, 'test-segment');

                await client.start();

                const { value: value1, report: report1 } = await policy.get('test');        // Cache lookup takes 100 + generate 50
                expect(value1.gen).to.equal(1);                                             // Fresh
                expect(report1.error).to.not.exist();

                await Hoek.wait(210);                                                       // Wait for stale

                const { value: value2, report: report2 } = await policy.get('test');        // Cache lookup takes 100, generate comes back after 50
                expect(value2.gen).to.equal(2);                                             // Fresh
                expect(report2.error).to.not.exist();

                const { value: value3, report: report3 } = await policy.get('test');        // Cache lookup takes 100
                expect(value3.gen).to.equal(2);                                             // Cached (100 left to stale)
                expect(report3.error).to.not.exist();

                client.connection.get = orig;
            });
github futurestudio / hapi-pulse / test / server-stop-calling-methods.js View on Github external
const server = new Hapi.Server()
    await server.register({
      plugin: require('../lib'),
      options: {
        logger: { error: () => {} },
        signals: 'ERRORPULSE',
        postServerStop: stub
      }
    })

    await server.start()

    process.emit('ERRORPULSE')

    // wait for the server to stop
    await Hoek.wait(100)
    expect(process.listenerCount('ERRORPULSE')).to.equal(0)

    Sinon.assert.called(process.exit)
    Sinon.assert.called(stub)

    // a stopped hapi server has a "started" timestamp of 0
    expect(server.info.started).to.equal(0)
  })
github futurestudio / hapi-pulse / test / server-stop-on-SIGTERM.js View on Github external
it('stops the server on SIGTERM', async () => {
    await server.start()
    // a stopped hapi server has a "started" timestamp of 0
    expect(server.info.started).to.not.equal(0)

    process.emit('SIGTERM')

    // wait for the server to stop
    await Hoek.wait(100)
    Sinon.assert.called(process.exit)

    // a stopped hapi server has a "started" timestamp of 0
    expect(server.info.started).to.equal(0)
  })
github academia-de-codigo / noire-server / test / modules / authorization / controllers / permission.js View on Github external
it('updates a permission', async flags => {
        // cleanup
        flags.onCleanup = function() {
            updateStub.restore();
        };

        // setup
        const fakePermission = { id: 1, action: 'create', resourceId: 10 };
        const entity = { description: 'potato' };
        const updateStub = Sinon.stub(PermissionService, 'update');
        updateStub.withArgs(fakePermission.id, entity).resolves(Hoek.merge(fakePermission, entity));

        server.route({
            method: 'PUT',
            path: '/permission/{id}',
            handler: PermissionCtrl.update
        });

        // exercise
        const response = await server.inject({
            method: 'PUT',
            url: `/permission/${fakePermission.id}`,
            payload: entity
        });

        // validate
        expect(updateStub.calledOnce).to.be.true();
github hapijs / nes / test / socket.js View on Github external
it('errors on invalid message', async () => {

            const server = Hapi.server();
            await server.register({ plugin: Nes, options: { auth: false } });

            const log = server.events.once('log');

            await server.start();
            const client = new Nes.Client('http://localhost:' + server.info.port);
            client.onError = Hoek.ignore;
            await client.connect();

            const a = { id: 1, type: 'other' };
            a.c = a;                    // Circular reference

            server.plugins.nes._listener._sockets._forEach((socket) => {

                socket._send(a, null, Hoek.ignore);
            });

            const [event] = await log;
            expect(event.data).to.equal('other');
            client.disconnect();
            await server.stop();
        });
github hydra-newmedia / hapi-sentry / index.js View on Github external
sentryEvent.level = event.channel;

        // use request credentials for capturing user
        if (opts.trackUser) sentryEvent.user = request.auth && request.auth.credentials;
        if (sentryEvent.user) {
          Object.keys(sentryEvent.user) // hide credentials
            .filter(prop => /^(p(ass)?w(or)?(d|t)?|secret)?$/i.test(prop))
            .forEach(prop => delete sentryEvent.user[prop]);
        }

        // some SDK identificator
        sentryEvent.sdk = { name: 'sentry.javascript.node.hapi', version };
        return sentryEvent;
      });

      Hoek.merge(scope, request.sentryScope);
      Sentry.captureException(event.error);
    });
  });
github hapijs / hapi / lib / cors.js View on Github external
if (!origin &&
        settings._origin !== false) {

        throw Boom.notFound('CORS error: Missing Origin header');
    }

    if (!exports.matchOrigin(origin, settings)) {
        return { message: 'CORS error: Origin not allowed' };
    }

    // Validate allowed headers

    let headers = request.headers['access-control-request-headers'];
    if (headers) {
        headers = headers.toLowerCase().split(/\s*,\s*/);
        if (Hoek.intersect(headers, settings._headers).length !== headers.length) {
            return { message: 'CORS error: Some headers are not allowed' };
        }
    }

    // Reply with the route CORS headers

    const response = h.response();
    response._header('access-control-allow-origin', settings._origin ? origin : '*');
    response._header('access-control-allow-methods', method);
    response._header('access-control-allow-headers', settings._headersString);
    response._header('access-control-max-age', settings.maxAge);

    if (settings.credentials) {
        response._header('access-control-allow-credentials', 'true');
    }
github hapijs / lab / lib / reporters / html.js View on Github external
}
            }

        });

        // Return original file descriptors (that will be flatten next) and generated file as well
        return Object.keys(descriptors).map((key) => descriptors[key]).concat([file]);
    });

    for (let i = 0; i < context.coverage.cov.files.length; ++i) {
        // Need to await for SourceMap.SourceMapConsumer
        const file = await context.coverage.cov.files[i];
        context.coverage.cov.files[i] = file;
    }

    context.coverage.cov.files = Hoek.flatten(context.coverage.cov.files);

    context.coverage.cov.files.forEach((file) => {

        file.segments = file.filename.split('/');
        file.basename = file.segments.pop();
        if (file.percent >= 0) {
            file.percent = (file.percent % 1 === 0) ? file.percent.toFixed() : file.percent.toFixed(2);
            file.percentClass = file.percent > 75 ? 'high' : (file.percent > 50 ? 'medium' : (file.percent > 25 ? 'low' : 'terrible'));
        }
        else {
            file.percentClass = 'hide';
        }

        if (file.segments.length) {
            file.dirname = file.segments.join('/') + '/';
        }