-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcanvas-api-request.js
63 lines (53 loc) · 1.45 KB
/
canvas-api-request.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
import request from 'request-promise-native';
import dotenv from 'dotenv';
dotenv.config();
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const repeatUntilSuccess = async promise => {
let tries = 0;
while (true) {
try {
return await promise;
} catch (e) {
tries++;
if (tries > 5) {
throw e;
}
await sleep(Math.random() * 100);
}
}
};
const canvasApiRequest = async (endpoint, arrayMap) => {
if (!process.env.BASE_URL) {
throw new Error('BASE_URL not defined');
}
if (!process.env.API_KEY || process.env.API_KEY.length < 10) {
throw new Error('API_KEY not defined');
}
if (!process.env.COURSE_ID) {
throw new Error('COURSE_ID not defined');
}
let url = `${process.env.BASE_URL}/api/v1/courses/${process.env.COURSE_ID}` + endpoint;
const options = { auth: { bearer: process.env.API_KEY }, json: true, resolveWithFullResponse: true };
if (!arrayMap) {
const response = await repeatUntilSuccess(request.get(url, options));
return response.body;
} else {
let returnArray = [];
while (url) {
const { body, headers } = await repeatUntilSuccess(request.get(url, options));
returnArray = returnArray.concat(arrayMap(body));
if (headers['link']) {
const match = headers['link'].match(/<([^>]+)>; rel="next"/);
if (match && match[1]) {
url = match[1];
} else {
url = null;
}
} else {
url = null;
}
}
return returnArray;
}
};
export default canvasApiRequest;