-
Notifications
You must be signed in to change notification settings - Fork 2
/
restletUtils.js
executable file
·125 lines (104 loc) · 2.58 KB
/
restletUtils.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
'use strict';
var request = require('request');
function executeRequest (method, uri, callback, config, body) {
request(
prepareRequest.call(this, method, uri, config, body),
completeRequest.bind(this, callback)
);
}
function prepareRequest (method, uri, config, body) {
if (isUndefined(config)) {
config = {};
}
var isJsonBody = typeof(body) === 'object' && !(body instanceof Buffer);
return {
method: method,
uri: uri,
qs: config.queryParameters,
headers: config.headers,
body: body,
json: isJsonBody
};
}
function completeRequest (callback, error, response, body) {
if (error) {
callback(error, body, response);
} else if (response.statusCode < 200 || response.statusCode > 299) {
callback({
status: response.statusCode,
message: response.body
}, body, response);
} else if (isJsonMimeType(response.headers['content-type'])) {
handleJson(callback, response, body);
} else {
callback(undefined, body, response);
}
}
function checkPathVariables () {
var errors = [];
for (var i = 0; i < arguments.length; i += 2) {
if (!isNumber(arguments[i]) && !isString(arguments[i]) && !isBoolean(arguments[i])) {
errors.push(arguments[i + 1]);
}
}
if (errors.length > 0) {
throw new Error(errors.join(', ') + ' must be defined');
}
}
function isDefined (value) {
return !isUndefined(value);
}
function isUndefined (value) {
return is(value, 'undefined');
}
function isString (value) {
return is(value, 'string');
}
function isBoolean (value) {
return is(value, 'boolean');
}
function isNumber (value) {
return is(value, 'number');
}
function isFunction (value) {
return is(value, 'function');
}
function isObject (value) {
return is(value, 'object');
}
function is (value, type) {
return typeof value === type;
}
function isJsonMimeType (contentType) {
return /^application\/(.*\\+)?json/.test(contentType);
}
function handleJson (callback, response, body) {
var error;
if (isString(body)) {
try {
body = JSON.parse(body);
} catch (e) {
error = {
status: 0,
message: 'Received JSON is invalid'
};
}
}
callback(error, body, response);
}
function stripTrailingSlash (value) {
return value.replace(/\/$/i, '');
}
function isEmpty (obj) {
return Object.keys(obj).length === 0;
}
module.exports = {
isString: isString,
isUndefined: isUndefined,
isDefined: isDefined,
isFunction: isFunction,
isEmpty: isEmpty,
stripTrailingSlash: stripTrailingSlash,
checkPathVariables: checkPathVariables,
executeRequest: executeRequest
};