UNPKG

lesca-fetcher

Version:

integrate fetch for easier use

58 lines (57 loc) 2.21 kB
var p = /* @__PURE__ */ ((t) => (t.URL_ENCODED = "application/x-www-form-urlencoded; charset=UTF-8", t.JSON = "application/json;charset=utf-8", t))(p || {}), m = /* @__PURE__ */ ((t) => (t[t.string = 0] = "string", t[t.JSON = 1] = "JSON", t))(m || {}); const w = { hostUrl: "https://jsonplaceholder.typicode.com/todos/1", contentType: "application/json;charset=utf-8", formatType: 1 /* JSON */ }; let d, h, u; const T = (t) => { const i = { ...w, ...t }, { hostUrl: o, contentType: s, formatType: n } = i; d = o.slice(-1) === "/" ? o.slice(0, -1) : o, u = n, h = new Headers({ "Content-Type": s }); }, g = (t) => { h.set("Authorization", `Bearer ${t}`); }, O = (t) => { Object.entries(t).forEach(([i, o]) => { h.set(i, o); }); }, l = (t = "/api") => t.slice(0, 1) === "/" ? `${d}${t}` : `${d}/${t}`, $ = (t = "/api", i, o) => { const s = "POST"; let n = JSON.stringify(i); return h.get("Content-Type") === "application/x-www-form-urlencoded; charset=UTF-8" && (n = Object.entries(i).map((e) => `${e[0]}=${e[1]}`).join("&")), o ? new Promise((e, a) => { const r = { ...o, Authorization: `Bearer ${h.get("Authorization")}` }; fetch(l(t), { method: s, body: n, headers: new Headers(r) }).then((c) => { c.json().then((f) => e(f)).catch((f) => a(f)); }).catch((c) => a(c)); }) : u === 1 ? new Promise((e, a) => { fetch(l(t), { method: s, body: n, headers: h }).then((r) => { r.json().then((c) => e(c)).catch((c) => a(c)); }).catch((r) => a(r)); }) : new Promise((e, a) => { fetch(l(t), { method: s, body: n, headers: h }).then((r) => { r.text().then((c) => e(c)).catch((c) => a(c)); }).catch((r) => a(r)); }); }, y = (t = "/api") => u === 1 ? new Promise((o, s) => { fetch(l(t), { method: "GET", headers: h }).then((n) => { n.json().then((e) => o(e)).catch((e) => s(e)); }).catch((n) => s(n)); }) : new Promise((o, s) => { fetch(l(t), { method: "GET", headers: h }).then((n) => { n.text().then((e) => o(e)).catch((e) => s(e)); }).catch((n) => s(n)); }), P = { install: T, post: $, get: y, setJWT: g, setHeader: O }; export { p as contentType, P as default, m as formatType, l as mergePath };