diff options
author | Joris | 2025-04-19 12:36:38 +0200 |
---|---|---|
committer | Joris | 2025-04-19 12:38:24 +0200 |
commit | 632eef6424d8dc8d40c2906177892697679e7b85 (patch) | |
tree | 48d9cd60e9e96eab810b5f7bb3c7b1fa79e0438f /frontend/ts/src/request.ts | |
parent | 063d8ef9eaf874a941f4459e831057dd0a1b7ddd (diff) |
Add ZIG server
Diffstat (limited to 'frontend/ts/src/request.ts')
-rw-r--r-- | frontend/ts/src/request.ts | 63 |
1 files changed, 63 insertions, 0 deletions
diff --git a/frontend/ts/src/request.ts b/frontend/ts/src/request.ts new file mode 100644 index 0000000..90906f9 --- /dev/null +++ b/frontend/ts/src/request.ts @@ -0,0 +1,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) + }) +} |