korean-dummy-json-fetcher
Version:
한국어 더미 데이터 생성 라이브러리
25 lines (24 loc) • 909 B
JavaScript
const BASE_URL = "https://koreandummyjson.site/api";
function buildQuery(params) {
if (!params)
return "";
const query = Object.entries(params)
.filter(([, v]) => v !== undefined)
.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
.join("&");
return query ? `?${query}` : "";
}
export async function fetcher(endpoint, options) {
const { method = "GET", params, body, headers } = options || {};
const url = `${BASE_URL}${endpoint}${buildQuery(params)}`;
const res = await fetch(url, {
method,
headers: Object.assign({ "Content-Type": "application/json" }, headers),
body: body ? JSON.stringify(body) : undefined,
});
if (!res.ok) {
const result = await res.json();
throw new Error(`API 요청 실패: ${res.status} ${res.statusText} - ${result.message}`);
}
return res.json();
}