export enum ContentType { JSON = "application/json", FORM_DATA = "multipart/form-data;", } export default abstract class BaseApiService { protected readonly backUrl = process.env["NEXT_PUBLIC_API_HOSTNAME"] + ":" + process.env["NEXT_PUBLIC_API_PORT"] + process.env["NEXT_PUBLIC_API_ROOT_URL"]; protected readonly proxyUrl = process.env["NEXT_PUBLIC_RPC_GATEWAY_HOSTNAME"] + ":" + process.env["NEXT_PUBLIC_RPC_GATEWAY_PORT"] + process.env["NEXT_PUBLIC_RPC_GATEWAY_ROOT_URL"]; // eslint-disable-next-line @typescript-eslint/no-empty-function protected constructor() {} protected buildHeaders(contentType: ContentType) { const headers = new Headers(); if (contentType === ContentType.JSON) { headers.set("Content-Type", contentType); } return headers; } protected buildBody(body: { [key: string]: unknown }): string { return JSON.stringify(body); } protected async getRequest(url: URL) { const request = async () => await fetch(url, { method: "GET", headers: this.buildHeaders(ContentType.JSON), }); return this.sendRequest(request); } protected async postRequest(url: URL, body: { [key: string]: unknown } = {}) { const request = async () => await fetch(url, { method: "POST", headers: this.buildHeaders(ContentType.JSON), body: this.buildBody(body), }); return this.sendRequest(request); } protected async putRequest(url: URL, body: { [key: string]: unknown } = {}) { const request = async () => await fetch(url, { method: "PUT", headers: this.buildHeaders(ContentType.JSON), body: this.buildBody(body), }); return this.sendRequest(request); } protected async patchRequest(url: URL, body: { [key: string]: unknown } = {}) { const request = async () => await fetch(url, { method: "PATCH", headers: this.buildHeaders(ContentType.JSON), body: this.buildBody(body), }); return this.sendRequest(request); } protected async deleteRequest(url: URL, body: { [key: string]: unknown } = {}) { const request = async () => await fetch(url, { method: "DELETE", headers: this.buildHeaders(ContentType.JSON), body: this.buildBody(body), }); return this.sendRequest(request); } protected async putFormDataRequest(url: URL, body: FormData) { const request = async () => await fetch(url, { method: "PUT", headers: this.buildHeaders(ContentType.FORM_DATA), body, }); return this.sendRequest(request); } private async sendRequest(request: () => Promise): Promise { const response = await request(); return this.processResponse(response, request); } protected async processResponse(response: Response, request: () => Promise): Promise { // eslint-disable-next-line @typescript-eslint/no-explicit-any let responseJson: any | null; try { responseJson = await response.json(); } catch (err: unknown) { responseJson = null; } if (!response.ok) { return Promise.reject(response); } return responseJson as T; } protected onError(error: unknown) { console.error(error); } } export interface IResponse { http_status: number; }