import { ApiParamsType, ApiRequestable } from './common.ts';
const handlerChild: ProxyHandler<GenericProxyApi> = { get(target: GenericProxyApi, p: PropertyKey, _receiver: any) { if (typeof p === 'symbol') { return (target as any)[p]; } const key = p.toString(); switch (key) { case 'toString': case 'valueOf': case 'toLocaleString': return (target as any)[p]; } return commonGet(key, target); }}
const commonGet = (key: string, target: GenericProxyApi) => { if (key.startsWith('$')) { if (key === '$') { return (id: string | number) => { const idStr = encodeURIComponent(String(id)); const child = new GenericProxyApi(target._apiEngine, `${target._path}/${idStr}`, `${target._model}/*`); return new Proxy(child, handlerChild); } } switch (key) { case '$get': case '$post': case '$delete': case '$put': case '$patch': case '$option': case '$head': { const fnc = (params: ApiParamsType) => { const mtd = key.substring(1); return target._apiEngine.doRequest(mtd, target._path, target._model, params); } return fnc.bind(target._apiEngine); } default: return (id: string | number) => { const idStr = encodeURIComponent(String(id)); const prefixKey = key.substring(1); const child = new GenericProxyApi(target._apiEngine, `${target._path}/${prefixKey}${idStr}`, `${target._model}/${prefixKey}*`); return new Proxy(child, handlerChild); } } } if (key.startsWith('_')) key = key.substring(1); const child = new GenericProxyApi(target._apiEngine, `${target._path}/${key}`, `${target._model}/${key}`); return new Proxy(child, handlerChild);}
const handlerRoot: ProxyHandler<GenericProxyApi> = { get(target: GenericProxyApi, p: PropertyKey, _receiver: any) { if (typeof p === 'symbol') { return (target as any)[p]; } const key = p.toString(); switch (key) { case 'toString': case 'valueOf': case 'toLocaleString': return target[p as 'toString' | 'valueOf' | 'toLocaleString']; } return commonGet(key, target); }}
class GenericProxyApi { public _apiEngine: ApiRequestable; public _path: string; public _model: string; constructor(apiEngine: ApiRequestable, path = '', model = path) { this._apiEngine = apiEngine; this._path = path; this._model = model; } toString(): string { return 'current path:' + this._path }}
export function buildProxy<T>(apiEngine: ApiRequestable, path = ''): T { return new Proxy(new GenericProxyApi(apiEngine, path), handlerRoot) as unknown as T;}