nuxt-spring-boot-showcase/frontend/app/API.ts
2025-11-19 20:22:22 -06:00

81 lines
2 KiB
TypeScript

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<DataTypeConfiguration> {
return this.call(APIMethod.GET, "/data");
}
readDataType(id: string): Promise<DataType> {
return this.call(APIMethod.GET, "/data/" + id);
}
deleteDataType(type: DataType): Promise<void> {
return this.call(APIMethod.DELETE, "/data/" + type.id);
}
saveDataType(type: DataType): Promise<DataTypeConfiguration> {
return this.call(APIMethod.POST, "/data", type);
}
/*
Helper methods
*/
private fullUrl(url: string): string {
return this.apiBaseUrl + url;
}
private requestOptions<A>(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<T, A>(
method: APIMethod,
url: string,
obj?: A
): Promise<T> {
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);
}
}