This repository has been archived by the owner on Oct 25, 2024. It is now read-only.
forked from jsforce/jsforce
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http-api.js
300 lines (267 loc) · 7.96 KB
/
http-api.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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
'use strict';
var inherits = require('inherits'),
events = require('events'),
_ = require('lodash/core'),
Promise = require('./promise');
/**
* HTTP based API class with authorization hook
*
* @constructor
* @extends events.EventEmitter
* @param {Connection} conn - Connection object
* @param {Object} [options] - Http API Options
* @param {String} [options.responseType] - Overriding content mime-type in response
* @param {Transport} [options.transport] - Transport for http api
* @param {Object} [options.noContentResponse] - Alternative response when no content returned in response (= HTTP 204)
*/
var HttpApi = function(conn, options) {
options = options || {};
this._conn = conn;
this.on('resume', function(err) { conn.emit('resume', err); });
this._responseType = options.responseType;
this._transport = options.transport || conn._transport;
this._noContentResponse = options.noContentResponse;
};
inherits(HttpApi, events.EventEmitter);
/**
* Callout to API endpoint using http
*
* @param {Object} request - Http Request object
* @param {String} request.url - Endpoint URL to request
* @param {String} request.method - Http method for request
* @param {Object} [request.headers] - Http request headers in hash object
* @param {Callback.<Object>} callback - Callback function
* @returns {Promise.<Object>} -
*/
HttpApi.prototype.request = function(request, callback) {
var self = this;
var conn = this._conn;
var logger = conn._logger;
var refreshDelegate = this.getRefreshDelegate();
// remember previous instance url in case it changes after a refresh
var lastInstanceUrl = conn.instanceUrl;
var deferred = Promise.defer();
var onResume = function(err) {
if (err) {
deferred.reject(err);
return;
}
// check to see if the token refresh has changed the instance url
if(lastInstanceUrl !== conn.instanceUrl){
// if the instance url has changed
// then replace the current request urls instance url fragment
// with the updated instance url
request.url = request.url.replace(lastInstanceUrl,conn.instanceUrl);
}
self.request(request).then(function(response) {
deferred.resolve(response);
}, function(err) {
deferred.reject(err);
});
};
if (refreshDelegate && refreshDelegate._refreshing) {
refreshDelegate.once('resume', onResume);
return deferred.promise.thenCall(callback);
}
// hook before sending
self.beforeSend(request);
self.emit('request', request);
logger.debug("<request> method=" + request.method + ", url=" + request.url);
var requestTime = Date.now();
return this._transport.httpRequest(request).then(function(response) {
var responseTime = Date.now();
logger.debug("elapsed time : " + (responseTime - requestTime) + "msec");
logger.debug("<response> status=" + response.statusCode + ", url=" + request.url);
self.emit('response', response);
// Refresh token if session has been expired and requires authentication
// when session refresh delegate is available
if (self.isSessionExpired(response) && refreshDelegate) {
refreshDelegate.refresh(requestTime, onResume);
return deferred.promise;
}
if (self.isErrorResponse(response)) {
var err = self.getError(response);
throw err;
}
return self.getResponseBody(response);
}, function(err) {
var responseTime = Date.now();
logger.debug("elapsed time : " + (responseTime - requestTime) + "msec");
logger.error(err);
throw err;
})
.thenCall(callback);
};
/**
* @protected
*/
HttpApi.prototype.getRefreshDelegate = function() {
return this._conn._refreshDelegate;
};
/**
*
* @protected
*/
HttpApi.prototype.beforeSend = function(request) {
request.headers = request.headers || {};
if (this._conn.accessToken) {
request.headers.Authorization = "Bearer " + this._conn.accessToken;
}
if (this._conn.callOptions) {
var callOptions = [];
for (var name in this._conn.callOptions) {
callOptions.push(name + "=" + this._conn.callOptions[name]);
}
request.headers["Sforce-Call-Options"] = callOptions.join(', ');
}
};
/**
* Detect response content mime-type
* @protected
*/
HttpApi.prototype.getResponseContentType = function(response) {
return this._responseType || response.headers && response.headers["content-type"];
};
/**
*
*/
HttpApi.prototype.parseResponseBody = function(response) {
var contentType = this.getResponseContentType(response);
var parseBody = /^(text|application)\/xml(;|$)/.test(contentType) ? parseXML :
/^application\/json(;|$)/.test(contentType) ? parseJSON :
/^text\/csv(;|$)/.test(contentType) ? parseCSV :
parseText;
try {
return parseBody(response.body);
} catch(e) {
return response.body;
}
};
/**
* Get response body
* @protected
*/
HttpApi.prototype.getResponseBody = function(response) {
if (response.statusCode === 204) { // No Content
return this._noContentResponse;
}
var body = this.parseResponseBody(response);
var err;
if (this.hasErrorInResponseBody(body)) {
err = this.getError(response, body);
throw err;
}
if (response.statusCode === 300) { // Multiple Choices
err = new Error('Multiple records found');
err.name = "MULTIPLE_CHOICES";
err.content = body;
throw err;
}
return body;
};
/** @private */
function parseJSON(str) {
return JSON.parse(str);
}
/** @private */
function parseXML(str) {
var ret = {};
require('xml2js').parseString(str, { explicitArray: false }, function(err, result) {
ret = { error: err, result : result };
});
if (ret.error) { throw ret.error; }
return ret.result;
}
/** @private */
function parseCSV(str) {
return require('./csv').parseCSV(str);
}
/** @private */
function parseText(str) { return str; }
/**
* Detect session expiry
* @protected
*/
HttpApi.prototype.isSessionExpired = function(response) {
return response.statusCode === 401;
};
/**
* Detect error response
* @protected
*/
HttpApi.prototype.isErrorResponse = function(response) {
return response.statusCode >= 400;
};
/**
* Detect error in response body
* @protected
*/
HttpApi.prototype.hasErrorInResponseBody = function(body) {
return false;
};
/**
* Parsing error message in response
* @protected
*/
HttpApi.prototype.parseError = function(body) {
var errors = body;
return _.isArray(errors) ? errors[0] : errors;
};
/**
* Get error message in response
* @protected
*/
HttpApi.prototype.getError = function(response, body) {
var error;
try {
error = this.parseError(body || this.parseResponseBody(response));
} catch(e) {}
error = _.isObject(error) && _.isString(error.message) ? error : {
errorCode: 'ERROR_HTTP_' + response.statusCode,
message : response.body
};
var err = new Error(error.message);
err.name = error.errorCode;
for (var key in error) { err[key] = error[key]; }
return err;
};
/*-------------------------------------------------------------------------*/
/**
* @protected
*/
var SessionRefreshDelegate = function(conn, refreshFn) {
this._conn = conn;
this._refreshFn = refreshFn;
this._refreshing = false;
};
inherits(SessionRefreshDelegate, events.EventEmitter);
/**
* Refresh access token
* @private
*/
SessionRefreshDelegate.prototype.refresh = function(since, callback) {
// Callback immediately When refreshed after designated time
if (this._lastRefreshedAt > since) { return callback(); }
var self = this;
var conn = this._conn;
var logger = conn._logger;
self.once('resume', callback);
if (self._refreshing) { return; }
logger.debug("<refresh token>");
self._refreshing = true;
return self._refreshFn(conn, function(err, accessToken, res) {
if (!err) {
logger.debug("Connection refresh completed.");
conn.accessToken = accessToken;
conn.emit("refresh", accessToken, res);
}
self._lastRefreshedAt = Date.now();
self._refreshing = false;
self.emit('resume', err);
});
};
/**
*
*/
HttpApi.SessionRefreshDelegate = SessionRefreshDelegate;
module.exports = HttpApi;