@volverjs/data
Version:
Repository pattern implementation with a tiny HttpClient based on Fetch API.
90 lines (89 loc) • 2.7 kB
JavaScript
var f = Object.defineProperty;
var o = (i, t, e) => t in i ? f(i, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : i[t] = e;
var h = (i, t, e) => o(i, typeof t != "symbol" ? t + "" : t, e);
import g from "qs";
class a {
constructor(t) {
h(this, "_options");
this._options = t;
}
extend(t) {
this._options = { ...this._options, ...t };
}
clone(t) {
return new a({ ...this._options, ...t });
}
build(t, e, n) {
return a.build(t, e, {
...this._options,
...n
});
}
query(t, e) {
return a.query(t, { ...this._options, ...e });
}
static build(t, e = {}, n) {
const s = Object.keys(e).filter((c) => e[c] !== void 0).reduce((c, u) => (c[u] = e[u], c), {}), { renderedPath: r, remainingParams: l } = a.path(
t,
s
), d = a.query(l, n);
return a._join(r, "?", d);
}
static query(t, e) {
if (Object.keys(t).length < 1)
return "";
const n = {
...e,
skipNulls: (e == null ? void 0 : e.skipNulls) ?? !0,
// default to true
format: (e == null ? void 0 : e.format) ?? "RFC1738",
// default to RFC1738
arrayFormat: (e == null ? void 0 : e.arrayFormat) ?? "comma",
// default to comma
encodeValuesOnly: (e == null ? void 0 : e.encodeValuesOnly) ?? !0
// default to true
};
return g.stringify(t, n);
}
static validatePathParam(t, e) {
const n = ["boolean", "string", "number"];
return Object.prototype.hasOwnProperty.call(t, e) ? n.includes(typeof t[e]) ? typeof t[e] == "string" && t[e].trim() === "" ? {
valid: !1,
message: `Path parameter ${e} cannot be an empty string.`
} : { valid: !0 } : {
valid: !1,
message: `Path parameter ${e} cannot be of type ${typeof t[e]}. Allowed types are: ${n.join(", ")}.`
} : {
valid: !1,
message: `Missing value for path parameter ${e}.`
};
}
static path(t, e = {}) {
const n = { ...e };
return { renderedPath: t.replace(
/\/?:[_A-Z]\w*\??/gi,
(r) => {
if (r === null)
return "";
const l = r.replace(/[:?/]/g, ""), { valid: d, message: c } = a.validatePathParam(
e,
l
);
if (r.includes("?") && !d)
return "";
if (!d)
throw new Error(c);
delete n[l];
const u = encodeURIComponent(e[l]);
return r != null && r.startsWith("/") ? `/${u}` : u;
}
), remainingParams: n };
}
static _join(t, e, n) {
const s = t.endsWith(e) ? t.slice(0, -e.length) : t, r = n.startsWith(e) ? n.slice(e.length) : n;
return s === "" || r === "" ? s + r : s + e + r;
}
}
export {
a as UrlBuilder
};