|
| 1 | +// SPDX-FileCopyrightText: 2025 Sidings Media <contact@sidingsmedia.com> |
| 2 | +// SPDX-License-Identifier: MIT |
| 3 | + |
| 4 | +import { useNotifications } from "@toolpad/core/useNotifications"; |
| 5 | +import { ApiError } from "./ApiError"; |
| 6 | +import type { Error } from "./responses/common"; |
| 7 | +import { NOTIFICATION_DISPLAY_TIME } from "./constants"; |
| 8 | + |
| 9 | +export type DecodeAs = "json" | "text" | "blob"; |
| 10 | + |
| 11 | +export class Api { |
| 12 | + private baseUrl: string = |
| 13 | + // @ts-expect-error |
| 14 | + (import.meta.env.VITE_API_URL as string | undefined) ?? |
| 15 | + "http://localhost:8080/v1/"; |
| 16 | + |
| 17 | + /** |
| 18 | + * Make a GET request to the API |
| 19 | + * @param path Endpoint path to call |
| 20 | + * @param options Standard fetch() options |
| 21 | + * @returns API response |
| 22 | + */ |
| 23 | + public async get<T>(path: string, options?: RequestInit): Promise<T> { |
| 24 | + const completeOptions = options ?? {}; |
| 25 | + return this.request(path, "get", completeOptions); |
| 26 | + } |
| 27 | + |
| 28 | + /** |
| 29 | + * Make a POST request to the API |
| 30 | + * @param path Endpoint path to call |
| 31 | + * @param options Standard fetch() options |
| 32 | + * @returns API response |
| 33 | + */ |
| 34 | + public async post<T>(path: string, options: RequestInit): Promise<T> { |
| 35 | + return this.request(path, "post", options); |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * Make a PUT request to the API |
| 40 | + * @param path Endpoint path to call |
| 41 | + * @param options Standard fetch() options |
| 42 | + * @returns API response |
| 43 | + */ |
| 44 | + public async put<T>(path: string, options: RequestInit): Promise<T> { |
| 45 | + return this.request(path, "put", options); |
| 46 | + } |
| 47 | + |
| 48 | + /** |
| 49 | + * Make a PATCH request to the API |
| 50 | + * @param path Endpoint path to call |
| 51 | + * @param options Standard fetch() options |
| 52 | + * @returns API response |
| 53 | + */ |
| 54 | + public async patch<T>(path: string, options: RequestInit): Promise<T> { |
| 55 | + return this.request(path, "patch", options); |
| 56 | + } |
| 57 | + |
| 58 | + /** |
| 59 | + * Make a DELETE request to the API |
| 60 | + * @param path Endpoint path to call |
| 61 | + * @param options Standard fetch() options |
| 62 | + * @returns API response |
| 63 | + */ |
| 64 | + public async delete<T>(path: string, options?: RequestInit): Promise<T> { |
| 65 | + const completeOptions = options ?? {}; |
| 66 | + return this.request(path, "delete", completeOptions); |
| 67 | + } |
| 68 | + |
| 69 | + /** |
| 70 | + * Make request to API. Generally one of the other methods (e.g. |
| 71 | + * get(), post() and so on) should be used rather than this one. Only |
| 72 | + * use this one if you need more flexibility (e.g. return a blob). |
| 73 | + * |
| 74 | + * @param path Endpoint path |
| 75 | + * @param method HTTP method |
| 76 | + * @param options Standard fetch() options |
| 77 | + * @param baseUrl Optional alternate base url to use |
| 78 | + * @param [decodeAs="json"] How should the response be decoded? Defaults |
| 79 | + * to `json`. |
| 80 | + * @param [contentType="application/json"] Content type to use. |
| 81 | + * `Defaults to application/json` |
| 82 | + * @returns API response |
| 83 | + */ |
| 84 | + public async request<T>( |
| 85 | + path: string, |
| 86 | + method: "get" | "post" | "put" | "patch" | "delete", |
| 87 | + options: RequestInit, |
| 88 | + baseUrl?: string, |
| 89 | + decodeAs: DecodeAs = "json", |
| 90 | + contentType = "application/json", |
| 91 | + ): Promise<T> { |
| 92 | + const opts = { |
| 93 | + ...options, |
| 94 | + method, |
| 95 | + }; |
| 96 | + |
| 97 | + opts.headers = { |
| 98 | + // eslint-disable-next-line @typescript-eslint/no-misused-spread |
| 99 | + ...opts.headers, |
| 100 | + "Content-type": contentType, |
| 101 | + ...this.headers(), |
| 102 | + }; |
| 103 | + |
| 104 | + let url: URL; |
| 105 | + if (baseUrl === undefined) { |
| 106 | + // Handle when base URL is set to relative path |
| 107 | + if (!this.baseUrl.startsWith("http")) { |
| 108 | + this.baseUrl = new URL(this.baseUrl, window.location.origin).toString(); |
| 109 | + } |
| 110 | + url = new URL(path, this.baseUrl); |
| 111 | + } else { |
| 112 | + url = new URL(path, baseUrl); |
| 113 | + } |
| 114 | + |
| 115 | + console.log(`Sending request: ${method.toUpperCase()} ${url.toString()}`); |
| 116 | + const response = await fetch(url.toString(), opts); |
| 117 | + if (!response.ok) { |
| 118 | + const data: Error = (await response.json()) as Error; |
| 119 | + throw new ApiError(data.message, data); |
| 120 | + } |
| 121 | + |
| 122 | + if (response.status === 204) { |
| 123 | + return undefined as T; |
| 124 | + } |
| 125 | + |
| 126 | + switch (decodeAs) { |
| 127 | + case "json": |
| 128 | + return response.json() as Promise<T>; |
| 129 | + case "text": |
| 130 | + return response.text() as Promise<T>; |
| 131 | + case "blob": |
| 132 | + return response.blob() as T; |
| 133 | + } |
| 134 | + } |
| 135 | + |
| 136 | + /** |
| 137 | + * Get the required headers for requests |
| 138 | + * @returns No headers needed |
| 139 | + */ |
| 140 | + private headers(): Record<string, string> { |
| 141 | + return {}; |
| 142 | + } |
| 143 | + |
| 144 | + /** |
| 145 | + * Create a URL using the configured base URL. |
| 146 | + * |
| 147 | + * @param path Path to append to base URL |
| 148 | + * @returns Correctly formatted URL |
| 149 | + */ |
| 150 | + public constructUrl(path: string): URL { |
| 151 | + // Handle when base URL is set to relative path |
| 152 | + if (!this.baseUrl.startsWith("http")) { |
| 153 | + this.baseUrl = new URL(this.baseUrl, window.location.origin).toString(); |
| 154 | + } |
| 155 | + return new URL(path, this.baseUrl); |
| 156 | + } |
| 157 | + |
| 158 | + public handleError( |
| 159 | + e: unknown, |
| 160 | + notifications: ReturnType<typeof useNotifications>, |
| 161 | + ): void { |
| 162 | + if (e instanceof ApiError) { |
| 163 | + notifications.show(e.error.message, { |
| 164 | + severity: "error", |
| 165 | + autoHideDuration: NOTIFICATION_DISPLAY_TIME, |
| 166 | + }); |
| 167 | + } else { |
| 168 | + notifications.show(`Network error: ${e}`, { |
| 169 | + severity: "error", |
| 170 | + autoHideDuration: NOTIFICATION_DISPLAY_TIME, |
| 171 | + }); |
| 172 | + } |
| 173 | + } |
| 174 | +} |
0 commit comments