设计模式-编写API包装器库打字稿

问题描述

遇到一些问题,试图提出一种编码方法。首先,我要说这不是我的强项,也没有尝试过类似的方法。

目标:为客户端创建包装API库。它应该公开一种使用basePath实例化lib的方法/类,然后公开其名称空间的对象/类及其上的调用内部API的方法,因此,使用者只需传递每个API调用所需的数据即可。简单,因此我们通常可以处理诸如错误之类的事情。

我知道我在这里无法工作-但这主要是为了了解我希望达到的目标。

我的问题是类似的

  • 是否应该通过静态方法设置basePath,而basePath只是一个属性?
  • 这又如何构成,以便我们可以共享方法和对basePath的访问,而不必每次都实例化它?

感谢所有帮助和建议。

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 methods that would be available  
}

// Exported to the consumer for ease of use. Others could be `Comments.postNewComment({user,data})`
class Posts extends Base {
  getAllPosts() {
    return this.get<PostsData>('/posts')
  }
}

// In the main index file for lib,it would export all the classes with available API methods (such as Posts,Auth,Comments etc) that the consumer would be able to use.
// Issue comes up when creating an instance of these because it would require the basePath again
export { Posts: new Posts(),Comments: new Comments() }; 

// Ideal usage: Main file of the app:
import LibName from 'lib-name'
new LibName({ basePath: 'api.whatever' }) // Left out re: brevity,but would be the class where we instantiate the basePath,and anything else

// In other locations through the app,be able to call the various methods from different sections (Auth.login,Comments.addNewComment etc)
import { Posts } from 'lib-name';
Posts.getAllPosts();

我一开始就遵循this article,但这的最后一个示例在一个导出(DevToClient.X)下公开了所有方法,而我希望将它们命名为其相应的父对象的命名空间。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)