-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.js
300 lines (261 loc) · 8.13 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
297
298
299
300
import { saveToken, getToken } from "./secureStore";
import axios from "axios";
// import dotenv from "dotenv";
// import { MACHINE_IP_ADDRESS } from "@env"
const BASE_URL = `http://${process.env.MACHINE_IP_ADDRESS}:8000/api`; // || process.env.REACT_APP_BASE_URL;
/** API Class.
*
* Static class tying together methods used to get/send to to the API.
* There shouldn't be any frontend-specific stuff here, and there shouldn't
* be any API-aware stuff elsewhere in the frontend.
*
*/
class RithmApi {
static async getAndSaveToken(cred) {
console.log("login (api file) called with data = ", cred);
let res;
try {
res = await axios.post(`${BASE_URL}/-token/`, cred);
console.log("login res = ", res);
} catch (err) {
console.log("login catch - error = ", err);
console.log("login catch - res = ", res);
return false;
}
const token = res.data.token;
console.log("token received = ", token);
await saveToken(token);
return true;
}
static async request(endpoint) {
console.debug("API Call:", endpoint);
const token = await getToken();
console.log("TOKEN IN REQUEST CALL = ", token);
const url = `${BASE_URL}/${endpoint}`;
console.log("request url = ", url);
const tokenHeaders = { Authorization: `Token ${token}` };
console.log("request headers = ", tokenHeaders);
try {
console.log("MAKING AXIOS REQUEST");
const res = await axios.get(url, { headers: tokenHeaders });
console.log("res from request inside try block = ", res);
return res;
} catch (err) {
console.error("API Error:", err);
}
}
// Individual API routes
/**
* Get all lecture sessions details
* Returns JSON:
* [
* {
"id": 0,
"lecture": "string",
"title": "string",
"description": "string",
"cohort": "string",
"dri": "string",
"staff": [
"string"
],
"week_group": "string",
"start_at": "2023-05-23T22:47:11.696Z",
"end_at": "2023-05-23T22:47:11.696Z",
"asset_set": [
"string"
],
"status": "private",
"api_url": "string"
}
* ]
*
*/
static async getDetailedLectureSessions() {
let res = await this.request("lecturesessions/");
const allLectureSessions = res.data.results;
console.log("allLectureSessions", allLectureSessions);
const pubLectureSessions = allLectureSessions.filter(
(l) => l.status === "published"
);
const lectureSessions = [];
for (const lect of pubLectureSessions) {
const endpoint = lect.api_url.split("/api/")[1];
let res = await this.request(endpoint);
lectureSessions.push(res.data);
}
lectureSessions.forEach((ls) => ls.type === "lecture");
return lectureSessions;
}
/**
* Get all exercise details
* Returns JSON:
* [{
"id": 0,
"title": "string",
"description": "string",
"exercise": "string",
"cohort": "string",
"dri": "string",
"week_group": "string",
"status": "private",
"api_url": "string",
"asset_set": [
"string"
],
"start_at": "2023-05-23T22:51:23.780Z",
"end_at": "2023-05-23T22:51:23.780Z",
"dri": "string",
"staff": [
"string"
]
}, ... ]
*
*/
static async getDetailedExerciseSessions() {
let res = await this.request("exercisesessions/");
const allExerciseSessions = res.data.results;
const pubExerciseSessions = allExerciseSessions.filter(
(ex) => ex.status === "published"
);
const exerciseSessions = [];
for (const exercise of pubExerciseSessions) {
const endpoint = exercise.api_url.split("/api/")[1];
let res = await this.request(endpoint);
let shared = { ...res.data };
delete shared.exerciselabsession_set;
let labSessions = res.data.exerciselabsession_set.map((session) => ({
...shared,
...session,
}));
exerciseSessions.push(...labSessions);
}
exerciseSessions.forEach((ex) => (ex.type = "exercise"));
return exerciseSessions;
}
/**
* Get all events details
* Returns JSON:
* [
{
"id": 0,
"slug": "string",
"title": "string",
"description": "string",
"cohort": "string",
"dri": "string",
"start_at": "2023-05-23T22:57:47.732Z",
"end_at": "2023-05-23T22:57:47.732Z",
"staff": [
"string"
],
"location": "string",
"week_group": "string",
"status": "private",
"api_url": "string",
"asset_set": [
"string"
]
}
* ]
*
*/
static async getDetailedEvents() {
let res = await this.request("events/");
const allEvents = res.data.results;
const pubEvents = allEvents.filter((evt) => evt.status === "published");
const events = [];
for (const evt of pubEvents) {
const endpoint = evt.api_url.split("/api/")[1];
let res = await this.request(endpoint);
events.push(res.data);
}
events.forEach((ev) => ev.type === "event");
return events;
}
/** getCurricByDay
*
* Returns all curric items (lectures, exercises, events) in JSON: [
*
* ]
*
*
*/
static async getCurricByDay() {
const lectureSessionPromise = this.getDetailedLectureSessions();
const exerciseSessionPromise = this.getDetailedExerciseSessions();
const eventPromise = this.getDetailedEvents();
const results = await Promise.allSettled([
lectureSessionPromise,
exerciseSessionPromise,
eventPromise,
]);
// const dayCurric = results.filter((thing) => {
// const curricDate = new Date(thing["start_at"]).toDateString();
// return curricDate === date;
// });
// Get all data from each of the promises that are fulfilled
let curricItems = results.map((result) => {
if (result.status === "fulfilled") {
return result.value;
}
});
// compile into one array
curricItems = curricItems.flat(1);
// sort this array by start at
curricItems.sort((a, b) => Date.parse(a.start_at) - Date.parse(b.start_at));
// initialize array to hold each of the arrays of curric items
let curricDays = [];
// while there are still items in our everything data array
while (curricItems.length > 0) {
// initialize empty array for that date
let dateCurricItems = [];
// initialize comparison variable (zeroth element)
let date = curricItems[0].start_at.slice(0, 10);
// while loop - iterate through sorted array of all curric events
while (
curricItems.length > 0 &&
date === curricItems[0].start_at.slice(0, 10)
) {
// compare string date to comparison variable
// if its the same, push item into array
// if its different, end inner loop
let item = curricItems.shift();
dateCurricItems.push(item);
}
curricDays.push(dateCurricItems);
}
// once outer while loop ends, return array of date items
return curricDays;
}
/** Get details on a company by handle. */
// static async getCompany(handle) {
// let res = await this.request(`companies/${handle}`);
// return res.company;
// }
// /** Get list of jobs (filtered by title if not undefined) */
// static async getJobs(title) {
// let res = await this.request("jobs", { title });
// return res.jobs;
// }
// /** Apply to a job */
// static async applyToJob(username, id) {
// await this.request(`users/${username}/jobs/${id}`, {}, "post");
// }
// /** Get token for login from username, password. */
// static async login(data) {
// let res = await this.request(`auth/token`, data, "post");
// return res.token;
// }
// /** Signup for site. */
// static async signup(data) {
// let res = await this.request(`auth/register`, data, "post");
// return res.token;
// }
// /** Save user profile page. */
// static async saveProfile(username, data) {
// let res = await this.request(`users/${username}`, data, "patch");
// return res.user;
// }
}
export default RithmApi;