-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathindex.js
92 lines (68 loc) · 2.1 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
'use strict';
const Boom = require('@hapi/boom');
const Defined = require('isdefined').has_value;
const internals = {};
/**
* Evaluates data as to whether it is an error or not and calls error or response as appropriate
* @param data
* @param meta
* @param options
* @returns {*}
*/
internals.calibrate = function (data, meta, options) {
if (data instanceof Error) {
return internals.error(data);
}
return internals.response(data, meta, options);
};
/**
* If error is a Boom error object, return as is
* Else return a Boom badImplementation error object
*/
internals.error = function (err) {
if (err.isBoom) {
return err;
}
return Boom.badImplementation(err);
};
/**
* If data is defined and non-null, wrap with statusCode and meta object properties
* Else return Boom notFound error object
*/
internals.response = function (data, _meta, _options) {
const meta = _meta || {};
const options = _options || {};
if (Defined(data)) {
return {
statusCode: 200,
data,
meta
};
}
const context = options.context ? `${options.context} ` : '';
const returnString =
options.return_string ||
options.returnString ||
`The ${context}resource with that ID does not exist or has already been deleted.`;
return Boom.notFound(returnString);
};
module.exports = internals.calibrate;
module.exports.error = internals.error;
module.exports.response = internals.response;
module.exports.hapi = {
name: 'calibrate',
register(server, { onResponse = true }) {
if (onResponse) {
const preResponse = function (request, h) {
const data = request.response.isBoom ? request.response : request.response.source;
return internals.calibrate(data);
};
server.ext('onPreResponse', preResponse);
return;
}
const calibrateDecorator = function (data, meta) {
return internals.calibrate(data, meta);
};
server.decorate('toolkit', 'calibrate', calibrateDecorator);
}
};