UNPKG

@volverjs/data

Version:

Repository pattern implementation with a tiny HttpClient based on Fetch API.

87 lines (86 loc) 2.38 kB
import u from "qs"; class s { _options; constructor(e) { this._options = e; } extend(e) { this._options = { ...this._options, ...e }; } clone(e) { return new s({ ...this._options, ...e }); } build(e, t, n) { return s.build(e, t, { ...this._options, ...n }); } query(e, t) { return s.query(e, { ...this._options, ...t }); } static build(e, t = {}, n) { const i = Object.keys(t).filter((o) => t[o] !== void 0).reduce((o, c) => (o[c] = t[c], o), {}), { renderedPath: r, remainingParams: a } = s.path( e, i ), l = s.query(a, n); return s._join(r, "?", l); } static query(e, t) { if (Object.keys(e).length < 1) return ""; const n = { ...t, skipNulls: t?.skipNulls ?? !0, // default to true format: t?.format ?? "RFC1738", // default to RFC1738 arrayFormat: t?.arrayFormat ?? "comma", // default to comma encodeValuesOnly: t?.encodeValuesOnly ?? !0 // default to true }; return u.stringify(e, n); } static validatePathParam(e, t) { const n = ["boolean", "string", "number"]; return Object.prototype.hasOwnProperty.call(e, t) ? n.includes(typeof e[t]) ? typeof e[t] == "string" && e[t].trim() === "" ? { valid: !1, message: `Path parameter ${t} cannot be an empty string.` } : { valid: !0 } : { valid: !1, message: `Path parameter ${t} cannot be of type ${typeof e[t]}. Allowed types are: ${n.join(", ")}.` } : { valid: !1, message: `Missing value for path parameter ${t}.` }; } static path(e, t = {}) { const n = { ...t }; return { renderedPath: e.replace( /\/?:[_A-Z]\w*\??/gi, (r) => { if (r === null) return ""; const a = r.replace(/[:?/]/g, ""), { valid: l, message: o } = s.validatePathParam( t, a ); if (r.includes("?") && !l) return ""; if (!l) throw new Error(o); delete n[a]; const c = encodeURIComponent(t[a]); return r?.startsWith("/") ? `/${c}` : c; } ), remainingParams: n }; } static _join(e, t, n) { const i = e.endsWith(t) ? e.slice(0, -t.length) : e, r = n.startsWith(t) ? n.slice(t.length) : n; return i === "" || r === "" ? i + r : i + t + r; } } export { s as UrlBuilder };