UNPKG

@volverjs/data

Version:

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

104 lines (103 loc) 2.86 kB
import h from "ky"; import { HTTPError as U, TimeoutError as _ } from "ky"; import { UrlBuilder as o } from "./UrlBuilder.js"; class l { _client; _urlBuilder; _prefixUrl; constructor(t = {}) { const { client: e, urlBuilder: r, searchParams: i, ...s } = t; this._client = e ?? h.create(s), this._urlBuilder = r ?? new o(i), this._prefixUrl = s.prefixUrl; } get = (t, e = {}) => { const { searchParams: r, ...i } = e; return this._client.get(this.buildUrl(t, r), i); }; post = (t, e = {}) => { const { searchParams: r, ...i } = e; return this._client.post( this.buildUrl(t, r), i ); }; put = (t, e = {}) => { const { searchParams: r, ...i } = e; return this._client.put(this.buildUrl(t, r), i); }; delete = (t, e = {}) => { const { searchParams: r, ...i } = e; return this._client.delete( this.buildUrl(t, r), i ); }; patch = (t, e = {}) => { const { searchParams: r, ...i } = e; return this._client.patch( this.buildUrl(t, r), i ); }; head = (t, e = {}) => { const { searchParams: r, ...i } = e; return this._client.head( this.buildUrl(t, r), i ); }; request = (t, e, r = {}) => { const { abortController: i, ...s } = r, { controller: c, signal: n } = l.createAbortController(i); return { responsePromise: this[t](e, { signal: n, ...s }), abort: (a) => c.abort(a), signal: n }; }; fetch = (t) => this._client(t); extend = (t = {}) => { const { searchParams: e, ...r } = t; this._client = this._client.extend(r), this._prefixUrl = r.prefixUrl ?? this._prefixUrl, this._urlBuilder.extend(e ?? {}); }; clone = (t = {}) => { const { searchParams: e, ...r } = t; return new l({ client: this._client.extend(r), urlBuilder: this._urlBuilder.clone(e) }); }; setBearerToken = (t, { headerName: e = "Authorization", prefix: r = "Bearer" } = {}) => { this.extend({ headers: { [e]: t ? `${r} ${t}` : void 0 } }); }; get stop() { return this._client.stop; } buildUrl(t, e) { const r = l.buildUrl(t, e, this._urlBuilder); return this._prefixUrl && typeof r == "string" && r?.startsWith("/") ? r.slice(1) : r; } static buildUrl = (t, e, r) => { if (l.isUrlTemplate(t)) { const { template: i, params: s } = t; return r ? r.build(i, s, e) : o.build(i, s, e); } return t; }; static isUrlTemplate(t) { return typeof t == "object" && t !== null && ((e) => ["template", "params"].every( (r) => e.includes(r) ))(Object.keys(t)); } static createAbortController = (t) => { const e = t ?? new AbortController(), { signal: r } = e; return { controller: e, signal: r }; }; } export { U as HTTPError, l as HttpClient, _ as TimeoutError };