-
Notifications
You must be signed in to change notification settings - Fork 2
/
RestClient.ts
402 lines (367 loc) · 12.2 KB
/
RestClient.ts
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
import { EventEmitter } from 'events';
import { format } from 'url';
import { stringify, parse } from 'querystring';
import { TOO_MANY_REQUESTS } from 'http-status';
import 'isomorphic-fetch';
import delay from 'delay.ts';
import * as pkg from './pkg';
import Token, { TokenStore, MemoryTokenStore } from './Token';
import isKnownReqBodyType from 'known-fetch-body';
import RCAccount from './RCAccount';
export const SERVER_PRODUCTION = 'https://platform.ringcentral.com';
export const SERVER_SANDBOX = 'https://platform.devtest.ringcentral.com';
export const API_VERSION = 'v1.0';
export const BASE_URL = '/restapi/';
const TOKEN_URL = BASE_URL + 'oauth/token';
const REVOKE_URL = BASE_URL + 'oauth/revoke';
const AUTHORIZE_URL = BASE_URL + 'oauth/authorize';
// Auth events
export const EventLoginStart = 'LoginStart';
export const EventLoginSuccess = 'LoginSuccess';
export const EventLoginError = 'LoginError';
export const EventRefreshStart = 'RefreshStart';
export const EventRefreshSuccess = 'RefreshSuccess';
export const EventRefreshError = 'RefreshError';
export const EventLogoutStart = 'LogoutStart';
export const EventLogoutSuccess = 'LogoutSuccess';
export const EventLogoutError = 'LogoutError';
/**
* A wrapper for sending http requests to RingCentralService.
*/
export default class RestClient extends EventEmitter {
server: string;
appKey: string;
appSecret: string;
handleRateLimit: boolean;
private recoverTime = 0; // In 429 status
tokenStore: TokenStore;
private gettingToken: Promise<Token>;
agents = [pkg.name + '/' + pkg.version];
constructor(opts: ClientOptions) {
super();
this.server = opts.server || SERVER_PRODUCTION;
this.appKey = opts.appKey;
this.appSecret = opts.appSecret;
this.tokenStore = opts.tokenStore || new MemoryTokenStore();
this.handleRateLimit = opts.handleRateLimit === false ? false : true;
let getToken = this.getToken;
this.getToken = (ownerInfo?: RCAccount) => {
if (!this.gettingToken) {
this.gettingToken = getToken.call(this, ownerInfo).then(t => {
this.gettingToken = null;
return t;
}, e => {
this.gettingToken = null;
throw e;
});
}
return this.gettingToken;
};
}
private basicAuth(): string {
return new Buffer(this.appKey + ':' + this.appSecret).toString('base64');
}
/**
* Throw exception if no valid token.
*/
async getToken(ownerInfo?: RCAccount) {
let token = await this.tokenStore.get();
if (token) {
token.validateOwner(this.appKey, ownerInfo);
if (!token.expired()) {
return token;
} else if (!token.refreshTokenExpired()) {
await this.refreshToken(token);
await this.tokenStore.save(token);
return token;
} else {
throw new Error('Token expired.');
}
} else {
throw new Error('Token not exist.');
}
}
/**
* Send http GET method
*/
get(url: string, query?: {}): Promise<Response> {
return this.call(url, query);
}
delete(url: string, query?: {}): Promise<Response> {
return this.call(url, query, { method: 'DELETE' });
}
/** Body can be Blob, FormData, URLSearchParams, String, Buffer or stream.Readable, any other type, plain object or instance of class will stringified as json. */
post(url: string, body: any, query?: {}): Promise<Response> {
return this.call(url, query, { method: 'POST', body: body });
}
/** Type of body is the same as post. */
put(url: string, body: any, query?: {}): Promise<Response> {
return this.call(url, query, { method: 'PUT', body: body });
}
// Handle rate limit.
async call(endpoint: string, query?: {}, opts?: RequestInit): Promise<Response> {
try {
return await this.sendApiCall(endpoint, query, opts);
} catch (e) {
if (this.handleRateLimit && e.code === TOO_MANY_REQUESTS) {
await delay(e['retryAfter']);
return await this.call(endpoint, query, opts);
}
throw e;
}
}
/**
* Perform an authenticated API call.
*/
private async sendApiCall(endpoint: string, query?: {}, opts?: RequestInit): Promise<Response> {
opts = opts || {};
opts.method = opts.method || 'GET';
let pathname: string;
if (endpoint.startsWith('http://') || endpoint.startsWith('https://')) {
pathname = endpoint;
} else {
pathname = this.server + BASE_URL + API_VERSION + endpoint;
}
let url = format({ pathname, query });
if (this.recoverTime) {
let timeLeft = this.recoverTime - Date.now();
if (timeLeft > 0) {
let e = new RestError(opts.method + ' ' + url + ': Throttled by rate limit', TOO_MANY_REQUESTS, 'Please retry after ' + timeLeft + ' milliseconds');
e['retryAfter'] = timeLeft;
throw e;
}
this.recoverTime = 0;
}
let token: Token;
try {
token = await this.getToken();
} catch (e) {
e.message = opts.method + ' ' + url + ', token error: ' + e.message;
e['code'] = 'NoToken';
throw e;
}
let headers = opts.headers = opts.headers || {};
headers['Authorization'] = token.type + ' ' + token.accessToken;
headers['Client-Id'] = this.appKey;
headers['X-User-Agent'] = this.agents.join(' ');
if (!isKnownReqBodyType(opts.body)) {
opts.body = JSON.stringify(opts.body);
headers['content-type'] = 'application/json';
}
let res = await fetch(url, opts);
if (!res.ok) {
let errorMessage = opts.method + ' ' + url + ': ';
let resBody, code;
if (isJsonRes(res)) {
resBody = await res.json();
errorMessage += resBody.message || resBody.error_description;
code = resBody.errorCode || resBody.error;
} else {
resBody = await res.text();
errorMessage += resBody;
code = 'Unknown';
}
let e = new RestError(errorMessage, code, resBody, res);
if (res.status === TOO_MANY_REQUESTS) {
e.code = TOO_MANY_REQUESTS;
// FIXME retry-after is custom header, by default, it can't be retrieved. Server should add header: 'Access-Control-Expose-Headers: retry-after'.
let retryAfter = parseInt(res.headers.get('retry-after') || '60') * 1000;
let newRecoverTime = Date.now() + retryAfter;
this.recoverTime = newRecoverTime > this.recoverTime ? newRecoverTime : this.recoverTime;
e['retryAfter'] = retryAfter;
}
throw e;
}
return res;
}
auth(opts: { username: string; password: string; extension?: string, accessTokenTtl?: number, refreshTokenTtl?: number, scope?: string[] }) {
let body = {
grant_type: 'password',
username: opts.username,
extension: opts.extension,
password: opts.password,
access_token_ttl: opts.accessTokenTtl,
refresh_token_ttl: opts.refreshTokenTtl,
scope: opts.scope && opts.scope.join(' ')
};
return this.authRequest(body, opts);
}
/**
* Login by oauth. http://ringcentral-api-docs.readthedocs.io/en/latest/oauth/
* @param callbackUrl The full oauth callback url with parameters returned from RingCentral.
*/
async oauthByUrl(callbackUrl: string, opts?: { accessTokenTtl: string; refreshTokenTtl: string }) {
let parts = callbackUrl.split('?');
let params = this.parseOauthCallback(parts[1]);
return await this.oauth(params.code, parts[0], opts);
}
async oauth(code: string, redirectUri: string, opts?: { accessTokenTtl: string; refreshTokenTtl: string }) {
let body = {
grant_type: 'authorization_code',
code: code,
redirect_uri: redirectUri,
access_token_ttl: opts && opts.accessTokenTtl,
refresh_token_ttl: opts && opts.refreshTokenTtl
};
return await this.authRequest(body);
}
/**
* Parse parameters from oauth.
* @param paramsStr The query part of the RingCentral oauth call back url.
*/
parseOauthCallback(paramsStr: string): OauthCallbackParams {
let params = parse(paramsStr);
if (!params.code) {
let e = new Error(params.error_description + '' || params.error + '' || 'No authorization code contained in the callback url.');
e['code'] = params.error;
throw e;
}
return <any>params;
}
oauthUrl(redirect_uri: string, opts?: { state?: string, force?: boolean }) {
let query = {
response_type: 'code',
client_id: this.appKey,
redirect_uri,
force: opts && opts.force,
state: opts && opts.state
};
return format({ pathname: this.server + AUTHORIZE_URL, query });
}
private async authRequest(body, user?: { username: string, extension?: string }) {
this.emit(EventLoginStart);
let startTime = Date.now();
let res = await fetch(this.server + TOKEN_URL, {
body: stringify(body),
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + this.basicAuth(),
'X-User-Agent': this.agents.join(' ')
}
});
if (res.ok) {
let resJson = await res.json();
let token = new Token();
token.setOwner(this.appKey, user);
await this.tokenStore.save(token.fromServer(resJson, Date.now() - startTime));
this.emit(EventLoginSuccess);
return token;
} else {
if (isJsonRes(res)) {
let resJson = await res.json();
let e = new RestError('RC platform auth fails: ' + (resJson.error_description || resJson.message),
resJson.error || resJson.errorCode,
resJson,
res);
this.emit(EventLoginError, e);
throw e;
} else {
let resText = await res.text();
let e = new RestError('RC platform auth fails: ' + resText, 'Unknown', resText, res);
this.emit(EventLoginError, e);
throw e;
}
}
}
async logout(): Promise<void> {
let token = await this.getToken();
this.emit(EventLogoutStart);
let res = await fetch(this.server + REVOKE_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + this.basicAuth(),
'X-User-Agent': this.agents.join(' ')
},
body: stringify({ token: token.accessToken })
});
if (res.ok) {
await this.tokenStore.clear();
this.emit(EventLogoutSuccess);
} else {
if (isJsonRes(res)) {
let resJson = await res.json();
let e = new RestError('Fail to logout RC platform: ' + (resJson.error_description || resJson.message),
resJson.error || resJson.errorCode,
resJson,
res);
this.emit(EventLogoutError, e);
throw e;
} else {
let resText = await res.text();
let e = new RestError('Fail to logout RC platform: ' + resText, 'Unknown', resText, res);
this.emit(EventLogoutError, e);
throw e;
}
}
}
/** Only one request will be sent at the same time. */
private async refreshToken(token: Token): Promise<void> {
let body = {
refresh_token: token.refreshToken,
grant_type: 'refresh_token',
endpoint_id: token.endpointId
};
let startTime = Date.now();
let res = await fetch(this.server + TOKEN_URL, {
method: 'POST',
body: stringify(body),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + this.basicAuth()
}
});
if (res.ok) {
let resJson = await res.json();
token.fromServer(resJson, Date.now() - startTime);
this.emit(EventRefreshSuccess);
} else {
if (isJsonRes(res)) {
let resJson = await res.json();
let e = new RestError('Fail to refresh token: ' + (resJson.error_description || resJson.message),
resJson.error || resJson.errorCode,
resJson,
res);
if (e.code === 'invalid_grant') { // Wrong token, clear them.
await this.tokenStore.clear();
}
this.emit(EventRefreshError, e);
throw e;
} else {
let resText = await res.text();
let e = new RestError('Fail to refresh token: ' + resText, 'Unknown', resText, res);
this.emit(EventRefreshError, e);
throw e;
}
}
}
}
function isJsonRes(res: Response) {
let ct = res.headers.get('content-type');
return ct && ct.match('application/json');
}
class RestError extends Error {
code: string;
detail: any; // http response json or text
rawRes: any; // The raw http response
constructor(message: string, code: string, detail?, raw?: Response) {
super(message);
this.code = code;
this.detail = detail;
this.rawRes = raw;
}
}
export interface OauthCallbackParams {
code: string; // The authorization code returned for your application
expires_in: number; // The remaining lifetime of the authorization code
state?: string; // This parameter will be included in response if it was specified in the client authorization request. The value will be copied from the one received from the client
}
export interface ClientOptions {
server?: string;
appKey: string;
appSecret: string;
/** Default TokenStore is MemoryTokenStore */
tokenStore?: TokenStore;
handleRateLimit?: boolean;
}