-
Notifications
You must be signed in to change notification settings - Fork 4
/
elvis-request.js
executable file
·104 lines (91 loc) · 2.73 KB
/
elvis-request.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
var HttpError = require('./http-error.js')
var Promise = require('bluebird');
var request = Promise.promisify(require('request').defaults({ jar: true , pool: {maxSockets: 5}}), { multiArgs: true });
Promise.promisifyAll(request, { multiArgs: true })
module.exports = (config) => {
var csrfToken;
function cloneObj(obj) {
return JSON.parse(JSON.stringify(obj));
}
function parseBody(result) {
try {
return JSON.parse(result[1]);
} catch (err) {
return result[1];
}
}
function authenticate() {
var options = {
method: 'POST',
url: (config.useBaseUrl ? '' : config.serverUrl) + '/services/login?username=' + config.username + '&password=' + config.password
}
console.log('Not logged in, logging in via:' + options.url);
return requestWithBodyErrorHandling(options).then(result => {
var body = config.parseJSON ? result : parseBody(result);
if (!body.loginSuccess) {
throw new HttpError(body.loginFaultMessage, 401, options);
} else {
if (body.csrfToken) {
// Elvis 6+
csrfToken = body.csrfToken;
}
return result;
}
});
}
function requestWithBodyErrorHandling(options) {
if(config.useBaseUrl) {
if(options.uri) {
options.uri = config.serverUrl + options.uri;
}
else {
options.url = config.serverUrl + options.url;
}
}
if (csrfToken) {
// Elvis 6+
options.headers = {
'X-CSRF-TOKEN': csrfToken
}
}
return request(options).then(result => {
var response = result[0];
var body = parseBody(result);
if (body && body.errorcode) {
response.statusCode = body.errorcode;
response.statusMessage = body.message;
}
// console.log('Elvis Response ' + JSON.stringify({
// statusCode: response.statusCode,
// options: options
// }, null, 2));
if (response.statusCode < 200 || response.statusCode > 299) {
throw new HttpError(response.statusMessage, response.statusCode, options);
} else if (config.parseJSON) {
return body;
} else {
return result;
}
});
}
return (options) => {
return requestWithBodyErrorHandling(cloneObj(options)).catch(error => {
var self = this;
if (error.statusCode == 401) {
if (!self.auth) {
self.auth = authenticate().then(() => {
self.auth = null;
return requestWithBodyErrorHandling(options);
});
return self.auth;
} else {
return self.auth.then(() => {
return requestWithBodyErrorHandling(options);
});
}
} else {
throw error;
}
});
}
}