How to use the @hapi/hoek.assert function in @hapi/hoek

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 hapijs / podium / lib / index.js View on Github external
criteria = internals.criteria(criteria);

    const name = criteria.name;
    Hoek.assert(name, 'Criteria missing event name');

    const event = this._eventListeners[name];
    Hoek.assert(event, `Unknown event ${name}`);

    if (!event.handlers &&
        !this._sourcePodiums.length) {

        return;
    }

    Hoek.assert(!criteria.channel || typeof criteria.channel === 'string', 'Invalid channel name');
    Hoek.assert(!criteria.channel || !event.flags.channels || event.flags.channels.indexOf(criteria.channel) !== -1, `Unknown ${criteria.channel} channel`);
    Hoek.assert(!event.flags.spread || Array.isArray(data) || typeof data === 'function', 'Data must be an array for spread event');

    if (typeof criteria.tags === 'string') {
        Object.assign({}, criteria);
        criteria.tags = { [criteria.tags]: true };
    }

    if (criteria.tags &&
        Array.isArray(criteria.tags)) {

        // Map array to object

        const tags = {};
        for (const tag of criteria.tags) {
            tags[tag] = true;
github hapijs / catbox / lib / policy.js View on Github external
if (!options ||
            !Object.keys(options).length) {

            return rule;
        }

        // Validate rule

        options = Joi.attempt(options, internals.schema, 'Invalid cache policy configuration');

        const hasExpiresIn = options.expiresIn !== undefined && options.expiresIn !== null;
        const hasExpiresAt = options.expiresAt !== undefined && options.expiresAt !== null;

        Hoek.assert(!hasExpiresIn || !options.staleIn || typeof options.staleIn === 'function' || options.staleIn < options.expiresIn, 'staleIn must be less than expiresIn');
        Hoek.assert(!options.staleIn || serverSide, 'Cannot use stale options without server-side caching');
        Hoek.assert(!options.staleTimeout || !hasExpiresIn || options.staleTimeout < options.expiresIn, 'staleTimeout must be less than expiresIn');
        Hoek.assert(!options.staleTimeout || !hasExpiresIn || typeof options.staleIn === 'function' || options.staleTimeout < (options.expiresIn - options.staleIn), 'staleTimeout must be less than the delta between expiresIn and staleIn');
        Hoek.assert(!options.staleTimeout || !options.pendingGenerateTimeout || options.staleTimeout < options.pendingGenerateTimeout, 'pendingGenerateTimeout must be greater than staleTimeout if specified');

        // Expiration

        if (hasExpiresAt) {

            // expiresAt

            const time = /^(\d\d?):(\d\d)$/.exec(options.expiresAt);
            rule.expiresAt = {
                hours: parseInt(time[1], 10),
                minutes: parseInt(time[2], 10)
            };
        }
        else {
github hapijs / call / lib / segment.js View on Github external
}
    else if (current.mixed) {

        // Mixed

        this._mixed = this._mixed || [];

        let mixed = this._mixedLookup(current);
        if (!mixed) {
            mixed = { segment: current, node: new internals.Segment() };
            this._mixed.push(mixed);
            this._mixed.sort(internals.mixed);
        }

        if (isEdge) {
            Hoek.assert(!mixed.node._edge, 'New route', record.path, 'conflicts with existing', mixed.node._edge && mixed.node._edge.record.path);
            mixed.node._edge = { segment: current, record };
        }
        else {
            mixed.node.add(remaining, record);
        }
    }
    else {

        // Parameter

        this._param = this._param || new internals.Segment();

        if (isEdge) {
            Hoek.assert(!this._param._edge, 'New route', record.path, 'conflicts with existing', this._param._edge && this._param._edge.record.path);
            this._param._edge = { segment: current, record };
        }
github metoikos / hapi-moon / commands / create-user.js View on Github external
const handleJobs = async () => {
    console.log(util.ColorOutput('FgYellow', 'Welcome to hapi-moon dump commandline utility'));
    let name = await question(`Please enter user's full name (min 2 char)`);
    let email = await question('Please enter user e-mail');
    let password = await question('Password (min 2 char)');

    const result = Joi.validate({
        name, email, password
    }, register, {abortEarly: false});

    Hoek.assert(result.error === null, result.error);

    const user = new User({
        name, email, password, active: true
    });
    await user.save();
};
github hapijs / wreck / lib / index.js View on Github external
request(method, url, options = {}) {

        try {
            options = Hoek.applyToDefaults(this._defaults, options, { shallow: internals.shallowOptions });

            Hoek.assert(options.payload === undefined || typeof options.payload === 'string' || typeof options.payload === 'object', 'options.payload must be a string, a Buffer, a Stream, or an Object');
            Hoek.assert(options.agent === undefined || options.agent === null || typeof options.rejectUnauthorized !== 'boolean', 'options.agent cannot be set to an Agent at the same time as options.rejectUnauthorized is set');
            Hoek.assert(options.beforeRedirect === undefined || options.beforeRedirect === null || typeof options.beforeRedirect === 'function', 'options.beforeRedirect must be a function');
            Hoek.assert(options.redirected === undefined || options.redirected === null || typeof options.redirected === 'function', 'options.redirected must be a function');
            Hoek.assert(options.gunzip === undefined || typeof options.gunzip === 'boolean' || options.gunzip === 'force', 'options.gunzip must be a boolean or "force"');
        }
        catch (err) {
            return Promise.reject(err);
        }

        if (options.baseUrl) {
            url = internals.resolveUrl(options.baseUrl, url);
            delete options.baseUrl;
        }

        const relay = {};
        const req = this._request(method, url, options, relay);
github hapijs / podium / lib / index.js View on Github external
internals.Podium.prototype.removeAllListeners = function (name) {

    Hoek.assert(this._eventListeners[name], `Unknown event ${name}`);
    this._eventListeners[name].handlers = null;
    return this;
};
github hapijs / joi / lib / utils.js View on Github external
exports.assertOptions = function (options, keys) {

    Hoek.assert(options && typeof options === 'object' && !Array.isArray(options), 'Options must be an object');
    const unknownKeys = Object.keys(options).filter((k) => !keys.includes(k));
    Hoek.assert(unknownKeys.length === 0, `Options contain unknown keys: ${unknownKeys}`);
};
github hapijs / hapi / lib / server.js View on Github external
decorate(type, property, method, options = {}) {

        Hoek.assert(this._core.decorations[type], 'Unknown decoration type:', type);
        Hoek.assert(property, 'Missing decoration property name');
        Hoek.assert(typeof property === 'string' || typeof property === 'symbol', 'Decoration property must be a string or a symbol');

        const propertyName = property.toString();
        Hoek.assert(propertyName[0] !== '_', 'Property name cannot begin with an underscore:', propertyName);

        const existing = this._core._decorations[type][property];
        if (options.extend) {
            Hoek.assert(type !== 'handler', 'Cannot extent handler decoration:', propertyName);
            Hoek.assert(existing, `Cannot extend missing ${type} decoration: ${propertyName}`);
            Hoek.assert(typeof method === 'function', `Extended ${type} decoration method must be a function: ${propertyName}`);

            method = method(existing);
        }
        else {
            Hoek.assert(existing === undefined, `${type[0].toUpperCase() + type.slice(1)} decoration already defined: ${propertyName}`);
        }
github antonsamper / hapi-cron / lib / index.js View on Github external
options.jobs.forEach((job) => {

            Hoek.assert(!jobs[job.name], 'Job name has already been defined');
            Hoek.assert(job.name, 'Missing job name');
            Hoek.assert(job.time, 'Missing job time');
            Hoek.assert(job.timezone, 'Missing job time zone');
            Hoek.assert(job.request, 'Missing job request options');
            Hoek.assert(job.request.url, 'Missing job request url');
            Hoek.assert(typeof job.onComplete === 'function' || typeof job.onComplete === 'undefined', 'onComplete value must be a function');

            try {
                jobs[job.name] = new CronJob(job.time, internals.trigger(server, job), null, false, job.timezone);
            }
            catch (err) {
                if (err.message === 'Invalid timezone.') {
                    Hoek.assert(!err, 'Invalid timezone. See https://momentjs.com/timezone for valid timezones');
                }
                else {
                    Hoek.assert(!err, 'Time is not a cron expression');
github hapijs / heavy / lib / index.js View on Github external
internals.Heavy.prototype.check = function () {

    if (!this.settings.sampleInterval) {
        return;
    }

    Hoek.assert(this._eventLoopTimer, 'Cannot check load when sampler is not started');

    const elapsed = this._loadBench.elapsed();
    const load = this.load;

    if (elapsed > this.settings.sampleInterval) {
        load.eventLoopDelay = Math.max(load.eventLoopDelay, elapsed - this.settings.sampleInterval);
    }

    if (this.settings.maxEventLoopDelay &&
        load.eventLoopDelay > this.settings.maxEventLoopDelay) {

        throw Boom.serverUnavailable('Server under heavy load (event loop)', load);
    }

    if (this.settings.maxHeapUsedBytes &&
        load.heapUsed > this.settings.maxHeapUsedBytes) {