-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
87 lines (73 loc) · 2.34 KB
/
utils.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
const fetch = require('node-fetch');
const FormData = require('form-data');
const { BASE_URL, REDIRECT_URI } = require('./config');
const { CLIENT_ID, CLIENT_SECRET } = process.env;
const TOKEN_URL = `${BASE_URL}/authorization/oauth2/token/`;
// Fetch timeout in milliseconds:
const TIMEOUT = 2500;
async function fetchJson(url, options) {
const res = await fetch(url, options);
const body = await res.json();
if (res.status >= 400) {
throw new Error(`Request to ${url} failed: ${JSON.stringify(body)}`);
}
return body;
}
/**
* Small wrapper around fetch that retries whenever a request exceeds TIMEOUT
* ms, and throws an error for status codes above 400.
*/
exports.callAPI = async function callAPI(url, accessToken, options) {
try {
const headers = accessToken ? { Authorization: `Bearer ${accessToken}` } : {};
const allOptions = Object.assign({}, options, {
headers: headers,
timeout: TIMEOUT,
});
return await fetchJson(url, allOptions);
} catch (e) {
if (e.type === 'request-timeout') {
console.warn('One of the requests timed out - retrying...');
return callAPI(url, accessToken, options);
}
throw e;
}
};
function getTokenForm() {
const form = new FormData();
form.append('client_id', CLIENT_ID);
form.append('client_secret', CLIENT_SECRET);
form.append('redirect_uri', REDIRECT_URI);
return form;
}
/**
* Posts to the OAuth2 token endpoint to retrieve an access and refresh token
* pair.
*/
exports.retrieveTokens = async function retrieveTokens(code) {
const form = getTokenForm();
form.append('grant_type', 'authorization_code');
form.append('code', code);
const body = await fetchJson(TOKEN_URL, {
method: 'POST',
body: form,
headers: form.getHeaders(),
});
return { access: body.access_token, refresh: body.refresh_token };
};
/**
* Posts to the OAuth2 token endpoint to refresh an existing token pair.
*/
exports.refreshTokens = async function refreshTokens(access, refresh) {
const form = getTokenForm();
form.append('grant_type', 'refresh_token');
form.append('refresh_token', refresh);
const body = await fetchJson(TOKEN_URL, {
method: 'POST',
body: form,
headers: Object.assign({}, form.getHeaders(), {
Authorization: `Bearer ${access}`,
}),
});
return { access: body.access_token, refresh: body.refresh_token };
};