I'm currently struggling to figure out how to code this API wrapper library. I want to create a wrapper API library for a client that allows them to easily instantiate the lib with a basePath and access namespaced objects/classes with methods that call into the internal API. The goal is to simplify the process for the consumer by only requiring them to pass in necessary data for each API call, while also handling errors generically.
I understand that what I have here won't work as is, but it gives an idea of my desired outcome.
Some questions I have are:
- Should the basePath be set from a static method and just be a property?
- How else could this be structured so we can share methods and access to the basePath without needing to reinstantiate it each time?
Any help and suggestions are greatly appreciated.
abstract class Base {
constructor(private basePath: string = '') {}
async get<T>(endpoint: string, config?: RequestInit | undefined): Promise<T> {
const response = await fetch(this.basePath + endpoint, config);
return response.json();
}
// ... other available methods
}
// Exported for ease of use. Other examples could include `Comments.postNewComment({user, data})`
class Posts extends Base {
getAllPosts() {
return this.get<PostsData>('/posts')
}
}
// Main index file for lib would export all classes with available API methods (Posts, Auth, Comments etc) for the consumer to use.
// An issue arises when creating an instance because it requires the basePath again
export { Posts: new Posts(), Comments: new Comments() };
// Ideal usage: Main app file:
import LibName from 'lib-name'
new LibName({ basePath: 'api.whatever' }) // Simplified version where we instantiate the basePath and anything else
// In various locations throughout the app, different sections can call the methods (Auth.login, Comments.addNewComment etc)
import { Posts } from 'lib-name';
Posts.getAllPosts();
I initially followed this article, but the final example exposes ALL methods under one export (DevToClient.X), whereas I prefer them namespaced under their appropriate parent object.