@itokun99/http
Version:
Fetch util for better fetching api
140 lines (139 loc) • 2.78 kB
JavaScript
const y = (e) => {
switch (e) {
case "url-enconded":
return "application/x-www-form-urlencoded";
case "json":
return "application/json";
default:
return;
}
}, i = (e, t, n) => {
if (e !== "GET")
return t === "form-data" ? n : JSON.stringify(n);
};
function k(e) {
const t = new URLSearchParams(e), n = {};
for (const [r, a] of t)
n[r] = a;
return n;
}
function l(e) {
if (!e || typeof e != "object" || Array.isArray(e))
return "";
const t = new URLSearchParams();
return Object.keys(e).forEach((n) => {
const r = e[n];
(typeof r == "string" || typeof r == "number") && t.append(n, r.toString());
}), t.toString();
}
function T(e, t, n) {
if (!e) return "";
let r = t ? `${e}/${t}` : e;
if (n) {
const a = l(n);
r = `${r}${a ? `?${a}` : ""}`;
}
return r;
}
async function p(e) {
return typeof e == "function" ? await e() : e;
}
const h = {
contentType: "json",
path: "",
withAppAuth: !0,
responseContentType: "json"
};
async function w(e, t, n, r) {
let a = { ...h, ...r };
const s = y(a == null ? void 0 : a.contentType);
let o = {};
s && (o["Content-Type"] = s), a.bearerToken && typeof a.bearerToken == "string" && (o.Authorization = `Bearer ${a.bearerToken}`), a.headers && (o = {
...o,
...a.headers
});
const c = await fetch(e, {
method: t,
headers: o,
...(a == null ? void 0 : a.signal) && { signal: a.signal },
body: i(t, a.contentType, n)
});
let u;
if (!c.ok)
throw await c.json();
switch (a.responseContentType) {
case "json":
u = await c.json();
break;
case "text":
u = await c.text();
break;
case "blob":
u = await c.blob();
break;
default:
u = await c.json();
break;
}
return u;
}
const f = async (e, t, n, r, a) => {
const s = await p(a), o = await p(r), c = T(
e,
(o == null ? void 0 : o.path) || (s == null ? void 0 : s.path) || "",
{
...s == null ? void 0 : s.metaParams,
...s == null ? void 0 : s.params,
...o == null ? void 0 : o.metaParams,
...o == null ? void 0 : o.params
}
), u = { ...s, ...o };
return w(c, t, n, u);
}, d = (e, t) => (n) => f(
e,
"GET",
void 0,
n,
t
), b = (e, t) => (n, r) => f(
e,
"POST",
n,
r,
t
), m = (e, t) => (n, r) => f(
e,
"PUT",
n,
r,
t
), g = (e, t) => (n, r) => f(
e,
"PATCH",
n,
r,
t
), j = (e, t) => (n) => f(
e,
"DELETE",
void 0,
n,
t
), P = {
get: d,
post: b,
put: m,
patch: g,
delete: j
};
export {
T as createEndpoint,
f as createRequest,
i as getBody,
y as getContentType,
P as http,
l as objectToSearchParams,
w as request,
p as resolveRequestOptions,
k as searchParamsToObject
};