55 lines
No EOL
1.7 KiB
TypeScript
55 lines
No EOL
1.7 KiB
TypeScript
/**
|
|
* TypedAPI Proxy with runtime type checking and IntelliSense support
|
|
*/
|
|
|
|
import type { RevolutionaryTypedFetch } from '../core/typed-fetch.js'
|
|
|
|
export class TypedAPIProxy {
|
|
private client: RevolutionaryTypedFetch<any>
|
|
private baseURL: string
|
|
private path: string[]
|
|
|
|
constructor(client: RevolutionaryTypedFetch<any>, baseURL: string, path: string[] = []) {
|
|
this.client = client
|
|
this.baseURL = baseURL
|
|
this.path = path
|
|
|
|
return new Proxy(this, {
|
|
get: (target, prop: string | symbol) => {
|
|
if (typeof prop !== 'string') return undefined
|
|
|
|
// Handle HTTP methods
|
|
if (['get', 'post', 'put', 'delete', 'patch'].includes(prop)) {
|
|
return async (idOrData?: any, data?: any) => {
|
|
const url = this.buildURL(idOrData && typeof idOrData !== 'object' ? idOrData : undefined)
|
|
const body = typeof idOrData === 'object' ? idOrData : data
|
|
|
|
switch (prop) {
|
|
case 'get':
|
|
return this.client.get(url)
|
|
case 'post':
|
|
return this.client.post(url, body)
|
|
case 'put':
|
|
return this.client.put(url, body)
|
|
case 'delete':
|
|
return this.client.delete(url)
|
|
default:
|
|
throw new Error(`Method ${prop} not supported`)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Handle property access for chaining
|
|
return new TypedAPIProxy(this.client, this.baseURL, [...this.path, prop])
|
|
}
|
|
})
|
|
}
|
|
|
|
private buildURL(id?: string): string {
|
|
let path = '/' + this.path.join('/')
|
|
if (id) {
|
|
path += `/${id}`
|
|
}
|
|
return path
|
|
}
|
|
} |