UNPKG

@httpc/client

Version:

httpc client for building function-based API with minimal code and end-to-end type safety

53 lines 2.08 kB
import { HttpCTypedClient } from "./typed"; import { isCall } from "./utils"; export function createClient(options = {}) { const client = new HttpCTypedClient(options); const { metadata, mode = metadata ? "strict" : "loose" } = options; const TARGET = () => { }; function createMethod(path, op) { return function (...args) { return op.access === "read" ? this.$client.read(path, ...args) : this.$client.write(path, ...args); }; } function createProxy(path, metadata) { return new Proxy(TARGET, { get(target, property, receiver) { if (path === "" && property in client) { return Reflect.get(client, property, receiver); } if (metadata && typeof property === "string") { const call = metadata[property]; if (call) { // check if it's a call if (isCall(call)) { return createMethod(joinPath(path, property), call); } else { // it's a tree return createProxy(joinPath(path, property), call); } } } if (mode === "loose" && typeof property === "string") { return createProxy(joinPath(path, property)); } throw new TypeError(`Can't find call '${path}'`); }, apply(target, thisArg, args) { if (mode !== "loose") { throw new TypeError(`Can't find call '${path}'`); } return client.$client.call(path, ...args); } }); } return createProxy("", metadata); } function joinPath(x, y) { if (!x) return y; return x.endsWith("/") ? `${x}${y}` : `${x}/${y}`; } //# sourceMappingURL=factory.js.map