-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.js
103 lines (68 loc) · 2.02 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
// const BASE_URL = `http://192.168.0.246:8000/api`;
const BASE_URL = "http://192.168.1.79:8000/api";
/** API Class.
*
*/
class SisApi {
static token = null;
static async request(endpoint, data = {}, method = "GET", isUrl=false) {
let url;
if (isUrl === false){
url = new URL(`${BASE_URL}/${endpoint}`);
}else {
url = new URL(endpoint);
}
let headers = {
'content-type': 'application/json',
};
if (this.token) {
headers['Authorization'] = `Token ${this.token}`;
}
url.search = (method === "GET")
? new URLSearchParams(data).toString()
: "";
// set to undefined since the body property cannot exist on a GET method
const body = (method !== "GET")
? JSON.stringify(data)
: undefined;
const resp = await fetch(url, { method, body, headers });
//fetch API does not throw an error, have to dig into the resp for msgs
if (!resp.ok) {
console.error("API Error:", resp.statusText, resp.status);
const { error } = await resp.json();
throw Array.isArray(error) ? error : [error];
}
return await resp.json();
}
/** Returns token upon logging in. */
static async login(username, password) {
const data = { username, password };
let res = await this.request(`-token/`, data, 'POST');
return res.token;
}
static async getLectures() {
let res = await this.request(`lecturesessions/`);
return res.results;
}
static async getLecture(id) {
let res = await this.request(`lecturesessions/${id}/`);
return res;
}
static async getStaffDetails(url){
let res = await this.request(url, {}, 'GET', true)
return res
}
static async getAllStaff(){
let res = await this.request(`staff/`)
return res.results;
}
static async getExercises() {
let res = await this.request(`exercisesessions/`);
return res.results;
}
static async getExercise(url) {
let res = await this.request(url, {}, 'GET', true);
return res;
}
}
export default SisApi;