-
Notifications
You must be signed in to change notification settings - Fork 22
/
api.js
296 lines (250 loc) Β· 7.42 KB
/
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
define([
'underscore',
'jquery',
'js/components/generic_module',
'js/components/api_request',
'js/mixins/dependon',
'js/components/api_response',
'js/components/api_query',
'js/components/api_feedback',
'js/mixins/hardened',
'js/mixins/api_access',
'moment',
], function(
_,
$,
GenericModule,
ApiRequest,
Mixin,
ApiResponse,
ApiQuery,
ApiFeedback,
Hardened,
ApiAccess,
Moment
) {
var Api = GenericModule.extend({
url: '/api/1/', // usually overriden during app bootstrap
clientVersion: null,
outstandingRequests: 0,
access_token: null,
refresh_token: null,
expires_at: null,
defaultTimeoutInMs: 60000,
activate: function(beehive) {
this.setBeeHive(beehive);
},
done: function(data, textStatus, jqXHR) {
// TODO: check the status responses
var response = new ApiResponse(data);
response.setApiQuery(this.request.get('query'));
this.api.trigger('api-response', response);
},
fail: function(jqXHR, textStatus, errorThrown) {
console.error(
'API call failed:',
JSON.stringify(this.request.url()),
jqXHR.status,
errorThrown
);
var pubsub = this.api.hasBeeHive() ? this.api.getPubSub() : null;
if (pubsub) {
var feedback = new ApiFeedback({
code: ApiFeedback.CODES.API_REQUEST_ERROR,
msg: textStatus,
request: this.request,
error: jqXHR,
psk: this.key || this.api.getPubSub().getCurrentPubSubKey(),
errorThrown: errorThrown,
text: textStatus,
beVerbose: true,
});
pubsub.publish(pubsub.FEEDBACK, feedback);
} else if (this.api)
this.api.trigger('api-error', this, jqXHR, textStatus, errorThrown);
},
initialize: function() {
this.always = _.bind(function() {
this.outstandingRequests--;
}, this);
},
getNumOutstandingRequests: function() {
return this.outstandingRequests;
},
// used by api_access.js
setVals: function(obj) {
_.each(
obj,
function(v, k) {
this[k] = v;
},
this
);
},
/**
* Before executing an ajax request, this will be passed
* the options and can modify them. Typically, clients
* make want to provide their own implementation.
*
* @param opts
*/
modifyRequestOptions: function(opts) {
// do nothing
},
hardenedInterface: {
request: 'make a request to the API',
setVals: 'set a value on API (such as new access token)',
},
});
Api.prototype._request = function(request, options) {
options = _.extend({}, options, request.get('options'));
var data;
var self = this;
var query = request.get('query');
if (query && !(query instanceof ApiQuery)) {
throw Error('Api.query must be instance of ApiQuery');
}
if (query) {
data =
options.contentType === 'application/json'
? JSON.stringify(query.toJSON())
: query.url();
}
var target = request.get('target') || '';
var u;
if (target.indexOf('http') > -1) {
u = target;
} else {
u =
this.url +
(target.length > 0 && target.indexOf('/') == 0
? target
: target
? '/' + target
: target);
}
u =
u.substring(0, this.url.length - 2) +
u.substring(this.url.length - 2, u.length).replace('//', '/');
if (!u) {
throw Error("Sorry, you can't use api without url");
}
var opts = {
type: 'GET',
url: u,
dataType: 'json',
data: data,
contentType: 'application/x-www-form-urlencoded',
context: { request: request, api: self },
timeout: this.defaultTimeoutInMs,
headers: {},
cache: true, // do not generate _ parameters (let browser cache responses),
};
if (options.timeout) {
opts.timeout = options.timeout;
}
if (this.clientVersion) {
opts.headers['X-BB-Api-Client-Version'] = this.clientVersion;
}
if (this.access_token) {
opts.headers.Authorization = this.access_token;
if (/accounts\/bootstrap/i.test(target)) {
opts.headers.Authorization = '';
}
}
// extend, rather than replace, the headers with user-supplied headers if any
_.extend(opts.headers, options.headers);
// one potential problem is that 'options' will override
// whatever is set above (other than headers) (so if sb wants to shoot himself/herself,
// we gave them the weapon... ;-))
_.extend(opts, _.omit(options, 'headers'));
this.outstandingRequests++;
this.modifyRequestOptions(opts, request);
// use the native fetch api for sending the request
// this can help with downloading blob and other non-text responses
if (options.useFetch && options.fetchOptions) {
var fetchOpts = _.assign(
{
credentials: 'include',
mode: 'cors',
timeout: this.defaultTimeoutInMs,
},
options.fetchOptions
);
fetchOpts.headers = _.assign(
{
'Content-Type': opts.contentType,
},
opts.headers,
options.fetchOptions.headers
);
var prom = window
.fetch(opts.url, fetchOpts)
.then(function(response) {
self.always.call(opts.context, response);
if (_.isFunction(opts.always)) {
opts.always.call(opts.context, response);
}
// handle any response errors (404, 500, etc.)
if (!response.ok) {
(opts.fail || self.fail).call(opts.context, response);
throw Error(response.statusText);
}
// otherwise call done
(opts.done || self.done).call(opts.context, response);
})
// handle network errors
.catch(function(error) {
(opts.fail || self.fail).call(opts.context, error);
throw Error(error);
});
// add a done property to the promise so it plays well with
// methods expecting jquery
return _.extend(prom, {
done: prom.then,
fail: prom.catch,
});
}
var jqXhr = $.ajax(opts)
.always(opts.always ? [this.always, opts.always] : this.always)
.done(opts.done || this.done)
.fail(opts.fail || this.fail);
jqXhr = jqXhr.promise(jqXhr);
return jqXhr;
};
// stubbable for testing
Api.prototype.getCurrentTimestamp = function () {
return Math.floor(Date.now() / 1000);
};
Api.prototype.request = function(request, options) {
var that = this;
var refreshRetries = 3;
var refreshToken = function() {
var d = $.Deferred();
var req = that.getApiAccess({ tokenRefresh: true, reconnect: true });
req.done(function() {
d.resolve(that._request(request, options));
});
req.fail(function() {
--refreshRetries > 0
? _.delay(refreshToken, 1000)
: d.reject.apply(d, arguments);
});
return d.promise();
};
if (!this.expires_at) {
return refreshToken();
}
// expires_at is in UTC, not local time
var expiration = this.expires_at;
var now = this.getCurrentTimestamp();
var difference = expiration - now;
// fewer than 2 minutes before token expires
if (difference < 120) {
return refreshToken();
}
return this._request(request, options);
};
_.extend(Api.prototype, Mixin.BeeHive, Hardened, ApiAccess);
return Api;
});