How to use hoek

Comprehensive hoek code examples:

How to use hoek.loadPackage:

222
223
224
225
226
227
228
229
230
231
        version: '/version',
        plugins: '/plugins'
    }
};

internals.version = Hoek.loadPackage().version;

exports.register = function (plugin, options, next) {

    var settings = Hoek.applyToDefaults(internals.defaults, options);

How to use hoek.ignore:

56
57
58
59
60
61
62
63
64
65
    handlers: {},
    extensions: {}
};
this._server = server;
this._dataStream = new Stream.Readable({ objectMode: true });
this._dataStream._read = Hoek.ignore;

// Options used to create Great Response
this._responseOptions = {
    requestHeaders: this.settings.requestHeaders,

How to use hoek.deepEqual:

497
498
499
500
501
502
503
504
505
506
    object: new Map(),
    function: new Map(),
    custom: new Map()
};

const compare = settings.comparator || Hoek.deepEqual;

for (let i = 0; i < value.length; ++i) {
    const item = settings.path ? Hoek.reach(value[i], settings.path) : value[i];
    const records = settings.comparator ? found.custom : found[typeof item];

How to use hoek.stringify:

210
211
212
213
214
215
216
217
218

    if (this.server._settings.debug &&
        this.server._settings.debug.request &&
        Hoek.intersect(tagsMap, this.server._settings.debug.request, true)) {

        console.error('Debug:', event.tags.join(', '), (data ? '\n    ' + (data.stack || (typeof data === 'object' ? Hoek.stringify(data) : data)) : ''));
    }
};

How to use hoek.inheritAsync:

7
8
9
10
11
12
13
14
15
16
var internals = {};


module.exports.Monitor = internals.ProcessMonitor = function () {

    Hoek.inheritAsync(internals.ProcessMonitor, process, ['uptime', 'memoryUsage']);
};


internals.ProcessMonitor.prototype.memory = function (callback) {

How to use hoek.Timer:

110
111
112
113
114
115
116
117
118
119
    }
});

// Lookup in cache

const timer = new Hoek.Timer();
this._get(id, (err, cached) => {

    if (err) {
        ++this.stats.errors;

How to use hoek.shallow:

65
66
67
68
69
70
71
72
73
74
};

// Massage registration config for use with rejoice
internals.registrationConfig = (options) => {

    const config = Hoek.shallow(options);
    delete config.defaults;
    delete config.teardownOnStop;

    // Resolve models

How to use hoek.once:

142
143
144
145
146
147
148
149
150
151
    if (callback) {
        return callback(err, res);
    }
};

finish = Hoek.once(finish);

var onError = function (err) {

    err.trace = _trace;

How to use hoek.escapeRegex:

298
299
300
301
302
303
304
305
306
        if (scheme instanceof RegExp) {
            customScheme = customScheme + scheme.source;
        }
        else {
            Hoek.assert(/[a-zA-Z][a-zA-Z0-9+-\.]*/.test(scheme), 'scheme at position ' + i + ' must be a valid scheme');
            customScheme = customScheme + Hoek.escapeRegex(scheme);
        }
    }
}

How to use hoek.Bench:

19
20
21
22
23
24
25
26
27
28
};


internals.ProcessMonitor.prototype.delay = function (callback) {

    var bench = new Hoek.Bench();
    setImmediate(function () {

        return callback(null, bench.elapsed());
    });

How to use hoek.cloneWithShallow:

85
86
87
88
89
90
91
92
93
94
});


internals.implementation = function (server, options) {

    let settings = Hoek.cloneWithShallow(options, 'provider');      // Options can be reused

    // Lookup provider

    if (typeof settings.provider === 'object') {

How to use hoek.intersect:

154
155
156
157
158
159
160
161
162
```javascript

var array1 = [1, 2, 3];
var array2 = [1, 4, 5];

var newArray = Hoek.intersect(array1, array2) // results in [1]
```

### flatten(array, target)

How to use hoek.applyToDefaultsWithShallow:

35
36
37
38
39
40
41
42
43
44
options = options || {};

Hoek.assert(this.constructor === internals.Monitor, 'Monitor must be instantiated using new');
Hoek.assert(plugin, 'plugin required to create monitor');

options = Hoek.applyToDefaultsWithShallow(internals.defaults, options, ['reporters', 'httpAgents', 'httpsAgents']);

// Force them to be arrays
var args = [];
options.httpAgents = args.concat(options.httpAgents || Http.globalAgent);

How to use hoek.base64urlEncode:

279
280
281
282
283
284
285
286
287
288
289
290
291
292
    });


    // Construct bewit: id\exp\mac\ext


    var bewit = credentials.id + '\\' + exp + '\\' + mac + '\\' + options.ext;
    return Hoek.base64urlEncode(bewit);
};




// Generate an authorization string for a message

How to use hoek.flatten:

51
52
53
54
55
56
57
58
59


internals.Alternatives.prototype.try = function (/* schemas */) {


    var schemas = Hoek.flatten(Array.prototype.slice.call(arguments));
    Hoek.assert(schemas.length, 'Cannot add other alternatives without at least one schema');

    var obj = this.clone();

How to use hoek.reach:

33
34
35
36
37
38
39
40
41
42
for (const [path, operations] of Object.entries(api.paths)) {
    const pathnames = Utils.unsuffix(path, '/').split('/').slice(1).join('.');

    for (const [method, operation] of Object.entries(operations)) {
        const pathsearch = `${pathnames}.${method}`;
        const handler = Hoek.reach(handlers, pathsearch);
        const xoptions = operation['x-hapi-options'] || {};

        if (!handler) {
            continue;

How to use hoek.base64urlDecode:

358
359
360
361
362
363
364
365
366
    return callback(Boom.badRequest('Multiple authentications'));
}

// Parse bewit

var bewitString = Hoek.base64urlDecode(resource[3]);
if (bewitString instanceof Error) {
    return callback(Boom.badRequest('Invalid bewit encoding'));
}

How to use hoek.escapeHtml:

228
229
230
231
232
233
234
235
236
### escapeHtml(string)

```javascript

var string = '<html> hey </html>';
var escapedString = Hoek.escapeHtml(string); // returns &lt;html&gt; hey &lt;/html&gt;
```

### escapeHeaderAttribute(attribute)

How to use hoek.merge:

39
40
41
42
43
44
45
46
47
48
        verifyOptions: { algorithms: [ 'HS256' ] },
    };
}

exports.register = function (server, options, next) {
    const config = Hoek.merge(generateDefaultOptions(), options);
    server.auth.strategy('jwt', 'jwt', config);
    server.auth.default('jwt');

    server.ext('onPreHandler', async (request, reply) => {

How to use hoek.mapToObject:

193
194
195
196
197
198
199
200
201
202
Convert an Array into an Object

```javascript

var array = [1,2,3];
var newObject = Hoek.mapToObject(array);   // results in [{"1": true}, {"2": true}, {"3": true}]

array = [{id: 1}, {id: 2}];
newObject = Hoek.mapToObject(array, "id"); // results in [{"id": 1}, {"id": 2}]
```

How to use hoek.unique:

125
126
127
128
129
130
131
132
133
134

```javascript

var array = [1, 2, 2, 3, 3, 4, 5, 6];

var newArray = Hoek.unique(array); // results in [1,2,3,4,5,6];

array = [{id: 1}, {id: 1}, {id: 2}];

newArray = Hoek.unique(array, "id") // results in [{id: 1}, {id: 2}]

How to use hoek.displayStack:

170
171
172
173
174
175
176
177
178
179

var err = new internals.Boom(500, message);

if (data && data.stack) {
    err.trace = data.stack.split('\n');
    err.outterTrace = Hoek.displayStack(1);
}
else {
    err.trace = Hoek.displayStack(1);
}

How to use hoek.nextTick:

95
96
97
98
99
100
101
102
103
104


internals.Policy.prototype._get = function (id, callback) {

    if (!this._cache) {
        return Hoek.nextTick(callback)(null, null);
    }

    this._cache.get({ segment: this._segment, id: id }, callback);
};

How to use hoek.applyToDefaults:

97
98
99
100
101
102
103
104
105
106

exports.methods.push({
    name: 'github.styleGuide',
    method: function () {

        const options = Hoek.applyToDefaults(internals.requestOptions, {
            headers: { accept: 'application/vnd.github.3.html' }
        });

        return Utils.download('https://api.github.com/repos/hapijs/assets/contents/Style.md', options);

How to use hoek.escapeHeaderAttribute:

116
117
118
119
120
121
122
123
124
125
var hasExt = artifacts.ext !== null && artifacts.ext !== undefined && artifacts.ext !== '';       // Other falsey values allowed
var header = 'Hawk id="' + credentials.id +
             '", ts="' + artifacts.ts +
             '", nonce="' + artifacts.nonce +
             (artifacts.hash ? '", hash="' + artifacts.hash : '') +
             (hasExt ? '", ext="' + Hoek.escapeHeaderAttribute(artifacts.ext) : '') +
             '", mac="' + mac + '"';

if (artifacts.app) {
    header += ', app="' + artifacts.app +

How to use hoek.clone:

14
15
16
17
18
19
20
21
22
internals.implementation = (server, options) => {

    Hoek.assert(options, 'Missing jwt auth strategy options');
    Hoek.assert(options.key, 'Missing required private key in configuration');

    const settings = Hoek.clone(options);

    const scheme = {
        authenticate: async (request, h) => {

How to use hoek.assert:

52
53
54
55
56
57
58
59
60
61

internals.Alternatives.prototype.try = function (/* schemas */) {


    var schemas = Hoek.flatten(Array.prototype.slice.call(arguments));
    Hoek.assert(schemas.length, 'Cannot add other alternatives without at least one schema');

    var obj = this.clone();

    for (var i = 0, il = schemas.length; i < il; ++i) {