38 lines
1.1 KiB
TypeScript
38 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');
|
|
}
|
|
|
|
const cachedResult = map.get(key);
|
|
if(cachedResult !== undefined){
|
|
return cachedResult;
|
|
}
|
|
|
|
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;
|
|
}; |