@httpc/client
Version:
httpc client for building function-based API with minimal code and end-to-end type safety
57 lines • 2.24 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.createClient = void 0;
const typed_1 = require("./typed");
const utils_1 = require("./utils");
function createClient(options = {}) {
const client = new typed_1.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 ((0, utils_1.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);
}
exports.createClient = createClient;
function joinPath(x, y) {
if (!x)
return y;
return x.endsWith("/") ? `${x}${y}` : `${x}/${y}`;
}
//# sourceMappingURL=factory.js.map