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 * as route from 'route'
export async function get<T>(path: string): Promise<T> {
return await request('GET', path, null, JSON.parse)
}
export async function post<T>(path: string, body: any = ''): Promise<T> {
return await request('POST', path, body, JSON.parse)
}
export async function post_(path: string, body: any = ''): Promise<void> {
return await request('POST', path, body, _ => {})
}
export async function put<T>(path: string, body: any = ''): Promise<T> {
return await request('PUT', path, body, JSON.parse)
}
export async function put_(path: string, body: any = ''): Promise<void> {
return await request('PUT', path, body, _ => {})
}
export async function del<T>(path: string, body: any = ''): Promise<T> {
return await request('DELETE', path, body, JSON.parse)
}
export async function del_(path: string, body: any = ''): Promise<void> {
return await request('DELETE', path, body, _ => {})
}
interface Message {
message: string
}
function request<T>(verb: string, path: string, body: any, f: (payload: string) => T): Promise<T> {
return new Promise((resolve, reject) => {
const xmlHttp = new XMLHttpRequest()
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
try {
resolve(f(xmlHttp.responseText))
} catch {
reject({ message: `Erreur de lecture de la réponse de requête réussie: ${xmlHttp.responseText}`})
}
} else {
// Redirect to /login when receiving a forbidden outside of /login
if (xmlHttp.status == 403 && window.location.pathname !== '/login') {
route.push(route.login)
} else {
try {
reject(JSON.parse(xmlHttp.responseText) as Message)
} catch {
reject({ message: `Erreur de lecture de la réponse de requête échouée: ${xmlHttp.responseText}`})
}
}
}
}
}
xmlHttp.open(verb, path, true);
xmlHttp.send(body)
})
}
|