import { notification } from "antd";
import { BaseApiResponse } from "@/utils/fetchExt";
import queryString from "query-string";
// Helper to retrieve auth token from localStorage
export function getAuthorization() {
const AccessTokenAdmin = localStorage.getItem("access_token");
if (AccessTokenAdmin) {
return { Authorization: `Bearer ${AccessTokenAdmin}` };
}
return undefined;
}
// Stage 1: Validate HTTP Status
export async function resposneStateHandler(response: Response) {
const { status, statusText } = response;
const releaseArr = [200, 304, 201];
if (releaseArr.includes(status)) {
return Promise.resolve(response);
} else {
console.warn("Error occurred", statusText);
return Promise.reject(response);
}
}
// Stage 2: Validate Business Code in JSON body
function responseCodeHandler<T>(response: BaseApiResponse<T>): Promise<BaseApiResponse<T>> {
const code = response.code || 0;
const message = response.message;
const codeArr = [0, 200];
if (codeArr.includes(Number(code))) {
return Promise.resolve(response);
}
notification.error({
message,
description: `[${code}]:${message}`,
});
return Promise.reject(response);
}
// Pipeline orchestrator
function responseHandle<T>(response: Response) {
return Promise.resolve(response)
.then((res) => resposneStateHandler(res))
.then((res) => res?.json())
.then((res) => responseCodeHandler<T>(res));
}
// GET request with query string support
export async function get<T>(url: string, data?: { [key: string]: unknown }): Promise<BaseApiResponse<T>> {
const locationSearch = data && queryString.stringify(data);
const finUrl = locationSearch ? `${url}?${locationSearch}` : url;
return fetch(finUrl, {
headers: {
"Content-Type": "application/json",
...getAuthorization(),
},
}).then((response) => responseHandle<T>(response));
}
// POST request
export function post<T>(Url: string, data?: any): Promise<BaseApiResponse<T>> {
return fetch(Url, {
method: "POST",
headers: {
"Content-Type": "application/json",
...getAuthorization(),
},
body: typeof data === "string" ? data : JSON.stringify(data),
}).then((response) => responseHandle<T>(response));
}
// PUT request
export async function put<T>(url: string, body: any): Promise<BaseApiResponse<T>> {
const response = await fetch(url, {
method: "PUT",
headers: { "Content-Type": "application/json", ...getAuthorization() },
body: JSON.stringify(body),
});
if (!response.ok) throw new Error(response.statusText);
return await response.json();
}
// DELETE request
export async function delet<T>(url: string, data?: any): Promise<BaseApiResponse<T>> {
const response = await fetch(url, {
method: "DELETE",
headers: { "Content-Type": "application/json", ...getAuthorization() },
body: JSON.stringify(data),
});
if (!response.ok) throw new Error(response.statusText);
return await response.json();
}