Skip to content

Instantly share code, notes, and snippets.

@jRimbault
Last active May 1, 2021 17:17
Show Gist options
  • Save jRimbault/2e2273381f8804cfe4beca4bca69dfe1 to your computer and use it in GitHub Desktop.
Save jRimbault/2e2273381f8804cfe4beca4bca69dfe1 to your computer and use it in GitHub Desktop.
/* In a config object :
{
"endpoints": {
"createUser": {
"path": "/users",
"method": "POST"
}
"listUsers": {
"path": "/users",
"method": "GET"
}
}
}
*/
interface Api {
listUsers(): Promise<User[]>;
createUser(params: { body: Omit<User, "uuid"> }): Promise<void>;
}
class Service {
private readonly serviceName = "";
public readonly api: Api;
constructor(
private readonly config: Config,
private readonly permissionService: PersmissionService,
private readonly http: HttpClient,
) {
this.api = this.buildProxy((name, ...args: any[]) => this.request(name, args[0]));
}
private async request<T>(route: keyof Api, params: { body?: unknown, path?: string }): Promise<T> {
// use imagination here, completely fake code
const method = this.config.endpoints[route].method;
const token = await this.permissionService.getTokenAsync(this.serviceName);
return this.http.request(this.serviceName, { path, method, payload: { body, token } });
}
private buildProxy<T>(action: (route: keyof T, ...args: unknown[})): T {
return new Proxy(
{},
{
get: (_target, name: string) => (...arg: unknown[]) => action(name as keyof T, ...arg),
}
) as T;
}
}
const service: Service = buildService();
await service.api.createUser({ /* */ });
const users = await service.api.listUsers();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment