better-auth
Version:
The most comprehensive authentication framework for TypeScript.
76 lines (74 loc) • 2.44 kB
JavaScript
import { isAtom } from "../utils/is-atom.mjs";
//#region src/client/proxy.ts
function getMethod(path, knownPathMethods, args) {
const method = knownPathMethods[path];
const { fetchOptions, query: _query, ...body } = args || {};
if (method) return method;
if (fetchOptions?.method) return fetchOptions.method;
if (body && Object.keys(body).length > 0) return "POST";
return "GET";
}
function createDynamicPathProxy(routes, client, knownPathMethods, atoms, atomListeners) {
function createProxy(path = []) {
return new Proxy(function() {}, {
get(_, prop) {
if (typeof prop !== "string") return;
if (prop === "then" || prop === "catch" || prop === "finally") return;
const fullPath = [...path, prop];
let current = routes;
for (const segment of fullPath) if (current && typeof current === "object" && segment in current) current = current[segment];
else {
current = void 0;
break;
}
if (typeof current === "function") return current;
if (isAtom(current)) return current;
return createProxy(fullPath);
},
apply: async (_, __, args) => {
const routePath = "/" + path.map((segment) => segment.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)).join("/");
const arg = args[0] || {};
const fetchOptions = args[1] || {};
const { query, fetchOptions: argFetchOptions, ...body } = arg;
const options = {
...fetchOptions,
...argFetchOptions
};
const method = getMethod(routePath, knownPathMethods, arg);
return await client(routePath, {
...options,
body: method === "GET" ? void 0 : {
...body,
...options?.body || {}
},
query: query || options?.query,
method,
async onSuccess(context) {
await options?.onSuccess?.(context);
if (!atomListeners || options.disableSignal) return;
/**
* We trigger listeners
*/
const matches = atomListeners.filter((s) => s.matcher(routePath));
if (!matches.length) return;
for (const match of matches) {
const signal = atoms[match.signal];
if (!signal) return;
/**
* To avoid race conditions we set the signal in a setTimeout
*/
const val = signal.get();
setTimeout(() => {
signal.set(!val);
}, 10);
}
}
});
}
});
}
return createProxy();
}
//#endregion
export { createDynamicPathProxy };
//# sourceMappingURL=proxy.mjs.map