Files
core_ng/server/clientAPI/APIPathGen.ts
T
2023-08-06 09:29:16 +00:00

37 lines
1.1 KiB
TypeScript

export function APIPathGen<T extends object, V>(
obj: T,
callback: (path: string[], tail: V, pathParam?: Record<string, string | number>) => unknown,
path: string[] = [],
): T {
const map = new Map<string, unknown>();
return new Proxy(obj, {
get(target, key) {
if(typeof key === 'symbol'){
throw new Error('Symbol is not supported');
}
if(map.has(key)){
return map.get(key)!;
}
const nextPath = [...path, key];
let next: T[keyof T];
if (key in target) {
next = target[key as keyof typeof target];
}
else {
throw `${nextPath} is not exists`;
}
if (typeof (next) === 'function') {
const result = callback(nextPath, next);
map.set(key, result);
return result;
}
const result = APIPathGen<T[keyof T], V>(next, callback, nextPath);
map.set(key, result);
return result;
}
}) as T;
};