From a8646f9f51fa944d516ac2ca92027c3ca6f6186f Mon Sep 17 00:00:00 2001 From: Leons Aleksandrovs <58330666+Skrazzo@users.noreply.github.com> Date: Sun, 13 Jul 2025 12:39:29 +0300 Subject: [PATCH] feat(requests): add delete and post function --- frontend/src/lib/requests.ts | 80 +++++++++++++++++++++++++++++++++++- 1 file changed, 79 insertions(+), 1 deletion(-) diff --git a/frontend/src/lib/requests.ts b/frontend/src/lib/requests.ts index 88cd4c2..2c19569 100644 --- a/frontend/src/lib/requests.ts +++ b/frontend/src/lib/requests.ts @@ -15,10 +15,18 @@ interface PostProps extends RequestProps { data: Record; } +interface PutProps extends RequestProps { + data: Record; +} + interface GetProps extends RequestProps { params?: Record; } +interface DeleteProps extends RequestProps { + params?: Record; +} + class Requests { constructor() {} @@ -54,7 +62,9 @@ class Requests { props.before?.(); // Get url parameters - const urlParams = props.params ? new URLSearchParams(props.params).toString() : ""; + const urlParams = props.params + ? new URLSearchParams(props.params).toString() + : ""; // Normalize url const finalUrl = normalizeLink(`${API_BASE}/${url}${urlParams}`); @@ -115,6 +125,74 @@ class Requests { props.finally?.(); } } + + async put(url: string, props: PutProps): Promise { + props.before?.(); + + // Normalize url + const finalUrl = normalizeLink(`${API_BASE}/${url}`); + + try { + // Do request + const res = await fetch(finalUrl, { + method: "PUT", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify(props.data), + }); + + // Verify data + const responseData = await this.verifyData(res); + + // Otherwise return response data + props.success?.(responseData); + return responseData; + } catch (error) { + const err = error as Error; + // Show notification, and call error callback + toast.error(err.message); + props.error?.(err); + } finally { + props.finally?.(); + } + } + + async delete(url: string, props: DeleteProps): Promise { + // Call before + props.before?.(); + + // Get url parameters + const urlParams = props.params + ? new URLSearchParams(props.params).toString() + : ""; + // Normalize url + const finalUrl = normalizeLink(`${API_BASE}/${url}${urlParams}`); + + try { + // Do request + const res = await fetch(finalUrl, { + method: "DELETE", + headers: { + "Content-Type": "application/json", + }, + }); + + // Verify data + const responseData = await this.verifyData(res); + + // Otherwise return response data + props.success?.(responseData); + return responseData; + } catch (error) { + const err = error as Error; + // Show notification, and call error callback + toast.error(err.message); + props.error?.(err); + } finally { + props.finally?.(); + } + } } export default new Requests();