From 632eef6424d8dc8d40c2906177892697679e7b85 Mon Sep 17 00:00:00 2001 From: Joris Date: Sat, 19 Apr 2025 12:36:38 +0200 Subject: Add ZIG server --- frontend/ts/src/request.ts | 63 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 frontend/ts/src/request.ts (limited to 'frontend/ts/src/request.ts') 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(path: string): Promise { + return await request('GET', path, null, JSON.parse) +} + +export async function post(path: string, body: any = ''): Promise { + return await request('POST', path, body, JSON.parse) +} + +export async function post_(path: string, body: any = ''): Promise { + return await request('POST', path, body, _ => {}) +} + +export async function put(path: string, body: any = ''): Promise { + return await request('PUT', path, body, JSON.parse) +} + +export async function put_(path: string, body: any = ''): Promise { + return await request('PUT', path, body, _ => {}) +} + +export async function del(path: string, body: any = ''): Promise { + return await request('DELETE', path, body, JSON.parse) +} + +export async function del_(path: string, body: any = ''): Promise { + return await request('DELETE', path, body, _ => {}) +} + +interface Message { + message: string +} + +function request(verb: string, path: string, body: any, f: (payload: string) => T): Promise { + 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) + }) +} -- cgit v1.2.3