-
Notifications
You must be signed in to change notification settings - Fork 143
Expand file tree
/
Copy pathgapi.js
More file actions
86 lines (72 loc) · 2.06 KB
/
gapi.js
File metadata and controls
86 lines (72 loc) · 2.06 KB
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
import loadjs from 'loadjs';
import once from 'lodash-es/once';
import promiseRetry from 'promise-retry';
import config from '../config';
import ExtendableError from '../util/ExtendableError';
export const SCOPES = [
'https://www.googleapis.com/auth/classroom.courses.readonly',
'https://www.googleapis.com/auth/classroom.coursework.students',
'https://www.googleapis.com/auth/classroom.coursework.me',
];
const DISCOVERY_DOCS = ['https://classroom.googleapis.com/$discovery/rest?version=v1'];
const RETRY_OPTIONS = {
retries: 16,
factor: 2,
minTimeout: 200,
maxTimeout: 4000,
};
class LoadError extends ExtendableError {}
let isGapiLoadedAndConfigured = false;
async function loadGapi() {
return promiseRetry(
async(retry) => {
try {
const gapi = await new Promise((resolve, reject) => {
loadjs('https://apis.google.com/js/client.js', {
success() {
resolve(window.gapi);
},
error(failedPaths) {
reject(new LoadError(`Failed to load ${failedPaths.join(', ')}`));
},
});
});
return await new Promise((resolve, reject) => {
gapi.load('client:auth2', {
callback: () => {
resolve(gapi);
},
onerror: reject,
timeout: 1000,
ontimeout: () => {
reject(new Error('Timed out'));
},
});
});
} catch (e) {
Reflect.deleteProperty(window, 'gapi');
return retry(e);
}
},
RETRY_OPTIONS,
);
}
export const loadAndConfigureGapi = once(async() => {
const gapi = await loadGapi();
await gapi.client.init({
apiKey: config.firebaseApiKey,
clientId: config.firebaseClientId,
discoveryDocs: DISCOVERY_DOCS,
scope: SCOPES.join(' '),
});
isGapiLoadedAndConfigured = true;
return gapi;
});
export function getGapiSync() {
if (!isGapiLoadedAndConfigured) {
throw new Error(
'Attempted to synchronously access `gapi` before it was loaded',
);
}
return window.gapi;
}