From 6ff2fe2acf83815c5b65cfcd49477bb56dec3845 Mon Sep 17 00:00:00 2001 From: baldo Date: Tue, 23 Aug 2022 15:18:22 +0200 Subject: [PATCH] Add DELETE method and more generic error handling to API helper. --- frontend/src/utils/Api.ts | 48 ++++++++++++++++++++++++++++++--------- 1 file changed, 37 insertions(+), 11 deletions(-) diff --git a/frontend/src/utils/Api.ts b/frontend/src/utils/Api.ts index d66dad5..effa6bc 100644 --- a/frontend/src/utils/Api.ts +++ b/frontend/src/utils/Api.ts @@ -2,12 +2,14 @@ import {SortDirection, toIsArray, type TypeGuard} from "@/types"; import type {Headers} from "request"; import {parseInteger} from "@/utils/Numbers"; +type Method = "GET" | "PUT" | "POST" | "DELETE"; + interface PagedListResult { entries: T[]; total: number; } -interface Response { +interface ApiResponse { result: T; headers: Headers; } @@ -36,20 +38,40 @@ class Api { return this.baseURL + this.apiPrefix + path + queryString; } - private async doGet(path: string, isT: TypeGuard, queryParams?: object): Promise> { + private async sendRequest(method: Method, path: string, queryParams?: object): Promise>; + private async sendRequest(method: Method, path: string, isT: TypeGuard, queryParams?: object): Promise>; + private async sendRequest(method: Method, path: string, isT?: TypeGuard, queryParams?: object): Promise> { const url = this.toURL(path, queryParams); - const result = await fetch(url); - const json = await result.json(); + const response = await fetch(url, { + method + }); - if (!isT(json)) { - console.log(json); - throw new Error(`API get result has wrong type. ${url} => ${json}`); + if (!response.ok) { + const body = await response.text(); + throw new Error(`API ${method} request failed: ${path} => ${response.status} - ${body}`); } - return { - result: json, - headers: result.headers, - }; + if (isT) { + const json = await response.json(); + if (isT && !isT(json)) { + console.log(json); + throw new Error(`API ${method} request result has wrong type. ${path} => ${json}`); + } + + return { + result: json, + headers: response.headers, + }; + } else { + return { + result: undefined as any as T, + headers: response.headers, + } + } + } + + private async doGet(path: string, isT: TypeGuard, queryParams?: object): Promise> { + return await this.sendRequest("GET", path, isT, queryParams); } async get(path: string, isT: TypeGuard): Promise { @@ -81,6 +103,10 @@ class Api { total, } } + + async delete(path: string): Promise { + await this.sendRequest("DELETE", path); + } } export const api = new Api();