-
Notifications
You must be signed in to change notification settings - Fork 1
๐ฝ Hyunxios: ๋ฐ์ดํฐ ํจ์น
Dunk edited this page Aug 25, 2024
·
1 revision
fetch๋ฐ์ ์ฌ์ฉํ์ง ๋ชปํ๋ ์ํฉ์ ํ์ฌ ์ฐ๋ฆฌ ์๋น์ค๋ ์ ์ฐฉ์ ์ด๋ฒคํธ๋ฅผ ์ด์์ค์ธ๋ฐ, fetch์ ์๋ timeout์ ์ถ๊ฐํ๊ณ HTTP method(get, post, patch ๋ฑ)๋ฅผ ํ๋ฒ๋ ๊ฐ์ธ ์ถ์ํํ์๋ค.
- ์๋ฌด๋๋ ์ ์ฐฉ์ ์ด๋ฒคํธ๋ฅผ ์ด์ํ๋ ์น์์ timeout์ ์ฝ๊ฒ ์ฌ์ฉํ ์ ์๋ Restful API ์ถ์ํ ๋ชจ๋์ด ํ์ํ๋ค. ๊ทธ๋์ Hyunxios๋ฅผ ๋ง๋ค๊ฒ ๋์๋ค.
- ํฐ ์ฃผ์์ ์์ด timeout์ ๋๋ฐฉํ ๋คํธ์ํฌ ์ถ์ํ ๋ชจ๋์ด ํ์ํ๋ค.
async get<T>(url: string): Promise<T> {
const headers = new Headers();
headers.append("Content-Type", "application/json");
try {
const response = await this.fetch(`${this.baseUrl}${url}`, {
method: "GET",
credentials: "include",
headers: headers,
redirect: "follow",
});
if (!response.ok) {
throw new Error("request failed.");
}
const data = (await response.json()) as T;
return data;
} catch {
throw new Error("parsing failed.");
}
}
ํ๋ฒํ ์ถ์ํ ํจ์์ด๋ค.
async fetch(
url: string,
options: object | null = null,
limitTime: number = 60000
): Promise<Response> {
const controller = new AbortController();
const { signal } = controller;
const fetchPromise = fetch(url, { ...options, signal }).then(
(response) => ({ type: "success", data: response })
);
const timeoutPromise = new Promise((_, reject) => {
setTimeout(() => {
controller.abort();
reject({ type: "error", data: "Request timed out" });
}, limitTime);
});
let result: Response = new Response();
try {
const raceResult = (await Promise.race([
fetchPromise,
timeoutPromise,
])) as { type: string; data: unknown };
console.log(raceResult.type);
if (raceResult.type === "error") throw new Error("Request timeout");
result = raceResult.data as Response;
} catch (error) {
console.log(`fetch error -> ${error}`);
}
return result;
}
timeout์ ์ถ๊ฐํ์ฌ Fetch APIํ๋ฒ wrappingํ๋ค.
- react query ์ ๊ฐ์ด polling ํ์์ ์ค์ ํ๊ณ ์์ฒด์ ์ผ๋ก ์ฒ๋ฆฌํ๋ ๋ก์ง์ ์ถ๊ฐํ ์ ์์ด์ผํ ๊ฒ ๊ฐ๋ค.
- ์ธ์คํด์ค๋ฅผ ์ ์ญ์ ์ผ๋ก ์์ฑํ์ง ์๊ณ custom hook์ ํตํด ์ ๋ฌํ๋ ๋ฐฉ์์ด ์กฐ๊ธ ๋ ๋ฆฌ์กํธ์ค๋ฌ์ด ๊ฒ ๊ฐ๋ค.