import type { DataType, DataTypeConfiguration } from "./types"; enum APIMethod { GET = "GET", POST = "POST", PUT = "PUT", DELETE = "DELETE", } export class API { private readonly apiBaseUrl: string; constructor(apiBaseUrl: string) { this.apiBaseUrl = apiBaseUrl; } readConfiguration(): Promise { return this.call(APIMethod.GET, "/data"); } readDataType(id: string): Promise { return this.call(APIMethod.GET, "/data/" + id); } deleteDataType(type: DataType): Promise { return this.call(APIMethod.DELETE, "/data/" + type.id); } saveDataType(type: DataType): Promise { return this.call(APIMethod.POST, "/data", type); } /* Helper methods */ private fullUrl(url: string): string { return this.apiBaseUrl + url; } private requestOptions(method: APIMethod, obj?: A): RequestInit { const headers: HeadersInit = new Headers(); const options: RequestInit = { method: method, headers: headers, }; if (obj !== undefined) { const objType = typeof obj; if (objType === "object") { options.body = JSON.stringify(obj); headers.set("Content-Type", "application/json; charset=UTF-8"); } else { throw new Error("Unsupported type: " + objType); } } return options; } private async call( method: APIMethod, url: string, obj?: A ): Promise { const options = this.requestOptions(method, obj); const response = await fetch(this.fullUrl(url), options); const status = response.status; const ok = status >= 200 && status < 400; if (ok) { return await response.json(); } else { const errorText = await response.text(); return Promise.reject(errorText); } } static instance(): API { const runtimeConfig = useRuntimeConfig(); // See the `nuxt.config.ts` file const apiBaseUrl = runtimeConfig.public.backend.baseUrl; return new API(apiBaseUrl); } }