aboutsummaryrefslogtreecommitdiff
path: root/frontend/ts/src/request.ts
diff options
context:
space:
mode:
Diffstat (limited to 'frontend/ts/src/request.ts')
-rw-r--r--frontend/ts/src/request.ts63
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)
+ })
+}