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) }) }