Files
frontend/apps/dc/app/components/api/index.ts
T

89 lines
2.4 KiB
TypeScript

import { DEV_URL_DC, LOCAL_URL } from "./config/env";
import { LoginApi } from "@/entities/auth";
import { SITE_ID } from "@/shared/config/env";
export async function fetchWithSilentRefresh(
input: RequestInfo | URL,
init: RequestInit,
): Promise<Response> {
const response = await fetch(input, init);
if (response.status !== 401) {
return response;
}
init.signal?.throwIfAborted();
await LoginApi.silentRefresh();
init.signal?.throwIfAborted();
return fetch(input, init);
}
export const getFetch = async (part : string, url: string, options?: Pick<RequestInit, "signal" | "cache">) => {
let reqUrl = "";
reqUrl = part === "dc" ? DEV_URL_DC+url : part === 'local' ? LOCAL_URL+url : DEV_URL_DC+url;
const response = await fetchWithSilentRefresh(reqUrl , {
method: "GET",
headers: {
accept: "application/json",
"X-Site-Id": SITE_ID,
},
...options,
});
if(!response.ok) {
throw new Error(`오류 발생: ${response.status}`);
}
const res = await response.json()
return res;
}
export const postFetch = async (part : string, url: string, params: unknown) => {
let reqUrl = "";
reqUrl = part === "dc" ? DEV_URL_DC+url : LOCAL_URL+url;
const response = await fetchWithSilentRefresh(reqUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Site-Id": SITE_ID,
},
body: JSON.stringify(params),
});
if(!response.ok) {
throw new Error(`오류 발생: ${response.status}`);
}
return await response.json();
}
export const putFetch = async (part : string, url: string, params: unknown) => {
let reqUrl = "";
reqUrl = part === "dc" ? DEV_URL_DC+url : LOCAL_URL+url;
const response = await fetchWithSilentRefresh(reqUrl, {
method: "PUT",
headers: {
"Content-Type": "application/json",
"X-Site-Id": SITE_ID,
},
body: JSON.stringify(params),
});
if(!response.ok) {
throw new Error(`오류 발생: ${response.status}`);
}
return response;
}
export const deleteFetch = async (part : string, url: string, params: unknown) => {
let reqUrl = "";
reqUrl = part === "dc" ? DEV_URL_DC+url : LOCAL_URL+url;
const response = await fetchWithSilentRefresh(reqUrl, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
"X-Site-Id": SITE_ID,
},
body: JSON.stringify(params),
});
if(!response.ok) {
throw new Error(`오류 발생: ${response.status}`);
}
return response;
}