This repository has been archived by the owner on Mar 21, 2024. It is now read-only.
forked from johnbrett/calibrate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
67 lines (53 loc) · 1.72 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
'use strict';
const Boom = require('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 = module.exports = 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 = module.exports.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 = module.exports.response = function (data, _meta, _options) {
const meta = _meta || {};
const options = _options || {};
if (Defined(data)) {
return {
statusCode: 200,
data: data,
meta: 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);
};
/**
* When used in plugin.register, will decorate the reply interface with the calibrate method
* so reply.calibrate() can be called
*/
const Decorate = require('./decorate');
internals.decorate = module.exports.decorate = Decorate;
internals.decorate.attributes = Decorate.attributes;