UNPKG

k6-trpc

Version:
91 lines 3.45 kB
var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; import { defaultTransformer, } from "@trpc/server"; import http from "k6/http"; require("https://jslib.k6.io/url/1.0.0/index.js"); const NONE = Symbol(); const OPTION = Symbol(); export const createOptions = (options) => { return Object.assign({ [OPTION]: "OPTION" }, options); }; const isCombinedDataTransformer = (transformer) => { return Object.prototype.hasOwnProperty.call(transformer, "input"); }; const isOptions = (opts) => { return (typeof opts === "object" && opts !== null && Object.prototype.hasOwnProperty.call(opts, OPTION)); }; const createFunctionHandler = (url, property, transformer) => { return (...args) => { let opts; let input = NONE; if (args.length === 2) { input = args[0]; if (isOptions(args[1])) { opts = args[1]; } } if (args.length === 1) { if (isOptions(args[0])) { opts = args[0]; } else { input = args[0]; } } let trimmedOpts; if (opts) { const _a = opts, _b = OPTION, _ = _a[_b], rest = __rest(_a, [typeof _b === "symbol" ? _b : _b + ""]); trimmedOpts = rest; } let serializedInput; if (input !== NONE) { if (isCombinedDataTransformer(transformer)) { serializedInput = JSON.stringify(transformer.input.serialize(input)); } else { serializedInput = JSON.stringify(transformer.serialize(input)); } } if (property === "query" && serializedInput === undefined) { return http.get(url, trimmedOpts); } if (property === "query") { return http.get(`${url}?input=${serializedInput}`, opts); } return http.post(url, serializedInput, trimmedOpts); }; }; const createProxyHandler = ({ url, transformer = defaultTransformer, }, path = "") => { return { get(_, property) { const base = new URL(path, url).toString(); const resource = path === "" ? property : path + "." + property; if (property === "query" || property === "mutate") { const target = createFunctionHandler(base, property, transformer); const handler = createProxyHandler({ url, transformer }, resource); return new Proxy(target, handler); } return createClientImplementation({ url, transformer }, resource); }, }; }; const createClientImplementation = ({ url, transformer = defaultTransformer, }, path = "") => { const handler = createProxyHandler({ url, transformer }, path); return new Proxy({}, handler); }; export const createClient = (url, transformer) => { if (!url.endsWith("/")) { url.concat("/"); } return createClientImplementation({ url, transformer }); }; //# sourceMappingURL=index.js.map