-
Notifications
You must be signed in to change notification settings - Fork 0
/
caller.js
139 lines (117 loc) · 3.25 KB
/
caller.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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
"use strict";
/**
* This makes request to the Lifelog Server
* @type {{}}
*/
var Promise = require('bluebird');
var request = require('request');
/**
* All Error Codes
* @type {{statusCode: number, title: string, description: string}[]}
*/
var ErrorCodes = [
{
statusCode: 401,
title: 'AccessDenied',
description: 'You do not have permission to access the requested resource. The error message may contain more information on why access was denied.'
},
{
statusCode: 402,
title: 'InsufficientAuthentication',
description: 'No access token was provided, or the provided access token was invalid. The error message may contain more information.'
},
{
statusCode: 404,
title: 'ResourceNotFound',
description: 'The requested resource does not exist.'
},
{
statusCode: 422,
title: 'AccessDenied',
description: 'The request could not be parsed or contained invalid values. The error message contains more information about which fields were invalid.'
}
];
/**
* Handle Rejection with Description
* @param err
* @returns {Function}
*/
var rejectHandler = function(err){
return function(reject){
if(err.description){
// If description is not set, then append from above
var obj;
for(var i = 0; i < ErrorCodes.length; i++){
if(err.code == ErrorCodes[i].statusCode){
err.description = ErrorCodes[i].description;
break;
}
}
}
reject(err);
};
};
/** Options for HTTPS Request **/
var options = {};
options.headers = {
'Accept': 'application/json',
'Accept-Encoding': 'gzip',
'Content-Encoding': 'gzip'
};
/**
* Make Request
* @param options
* @returns {bluebird}
*/
var Caller = {};
Caller.makeRequest = function(url, token, parseJSON){
/** Set options **/
options.headers['Authorization'] = 'Bearer ' + token;
options.url = url;
return new Promise(function (resolve, reject) {
request(options, function(err, response, body){
if(err){
rejectHandler(err);
}
else{
if (parseJSON) {
try {
body = JSON.parse(body);
resolve(body);
} catch(err){
resolve(body);
}
} else {
resolve(body);
}
}
});
});
};
/**
* Make Post Request
* @param customObj
* @returns {bluebird}
*/
Caller.makePostRequest = function(customObj, parseJSON){
return new Promise(function (resolve, reject) {
request.post(customObj, function(err, response, body){
if(err){
rejectHandler(err);
}
else{
if(parseJSON){
try{
body = JSON.parse(body);
resolve(body);
} catch(err){
resolve(body);
}
} else {
resolve(body);
}
}
});
});
};
module.exports = Caller;