Skip to content

๐Ÿ’ฝ Hyunxios: ๋ฐ์ดํ„ฐ ํŒจ์น˜

Dunk edited this page Aug 25, 2024 · 1 revision

์†Œ๊ฐœ

fetch๋ฐ–์— ์‚ฌ์šฉํ•˜์ง€ ๋ชปํ•˜๋Š” ์ƒํ™ฉ์— ํ˜„์žฌ ์šฐ๋ฆฌ ์„œ๋น„์Šค๋Š” ์„ ์ฐฉ์ˆœ ์ด๋ฒคํŠธ๋ฅผ ์šด์˜์ค‘์ธ๋ฐ, fetch์— ์—†๋˜ timeout์„ ์ถ”๊ฐ€ํ•˜๊ณ  HTTP method(get, post, patch ๋“ฑ)๋ฅผ ํ•œ๋ฒˆ๋” ๊ฐ์‹ธ ์ถ”์ƒํ™”ํ•˜์˜€๋‹ค.

์ฃผ์•ˆ์ 

  1. ์•„๋ฌด๋ž˜๋„ ์„ ์ฐฉ์ˆœ ์ด๋ฒคํŠธ๋ฅผ ์šด์˜ํ•˜๋Š” ์›น์—์„  timeout์„ ์‰ฝ๊ฒŒ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” Restful API ์ถ”์ƒํ™” ๋ชจ๋“ˆ์ด ํ•„์š”ํ–ˆ๋‹ค. ๊ทธ๋ž˜์„œ Hyunxios๋ฅผ ๋งŒ๋“ค๊ฒŒ ๋˜์—ˆ๋‹ค.
  2. ํฐ ์ฃผ์•ˆ์ ์—†์ด timeout์„ ๋™๋ฐฉํ•œ ๋„คํŠธ์›Œํฌ ์ถ”์ƒํ™” ๋ชจ๋“ˆ์ด ํ•„์š”ํ–ˆ๋‹ค.

hyunxios ๊ตฌ์กฐ

hyunxios

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ํ–ˆ๋‹ค.

์ถ”ํ›„ ์ˆ˜์ •์‚ฌํ•ญ

  1. react query ์™€ ๊ฐ™์ด polling ํƒ€์ž„์„ ์„ค์ •ํ•˜๊ณ  ์ž์ฒด์ ์œผ๋กœ ์ฒ˜๋ฆฌํ•˜๋Š” ๋กœ์ง์„ ์ถ”๊ฐ€ํ•  ์ˆ˜ ์žˆ์–ด์•ผํ•  ๊ฒƒ ๊ฐ™๋‹ค.
  2. ์ธ์Šคํ„ด์Šค๋ฅผ ์ „์—ญ์ ์œผ๋กœ ์ƒ์„ฑํ•˜์ง€ ์•Š๊ณ  custom hook์„ ํ†ตํ•ด ์ „๋‹ฌํ•˜๋Š” ๋ฐฉ์‹์ด ์กฐ๊ธˆ ๋” ๋ฆฌ์•กํŠธ์Šค๋Ÿฌ์šด ๊ฒƒ ๊ฐ™๋‹ค.