如何将自定义AxiosInstance传入openapi-generator生成的TypeScript类?
解决openapi-generator typescript-axios模板传入自定义AxiosInstance的问题
不用折腾原型链,生成的每个API类(比如你用的HotelsRestServiceApi)的构造函数本身就支持传入自定义Axios实例,直接在实例化时传第三个参数就行。
正确写法
import { HotelsRestServiceApi, Configuration } from '../../generated/openapi'; import { axiosClientNoAuth } from '../index'; // 你的自定义AxiosInstance const config = new Configuration({ basePath: 'http://localhost:8080', }); // 直接在实例化API类时传入自定义axios实例 const hotelsApi = new HotelsRestServiceApi(config, undefined, axiosClientNoAuth); // 后续正常调用API方法即可 // hotelsApi.getSomeHotelData().then(res => console.log(res));
为什么你的原方法行不通
- 你修改
prototype.__proto__的方式既不符合TypeScript类型规范,也完全没必要——生成的HotelsRestServiceApi本身就继承自BaseAPI,原型链本来就是通的。 BaseAPI的构造函数确实接受三个参数(config、basePath、axios实例),而每个具体的API类构造函数会把这三个参数透传给父类BaseAPI,所以直接在实例化具体API类时传第三个参数就搞定了。
进阶优化:统一管理API实例
如果所有API类都要用同一个自定义Axios实例,可以封装个工厂函数避免重复代码:
import { Configuration } from '../../generated/openapi'; import { axiosClientNoAuth } from '../index'; import { HotelsRestServiceApi, AnotherRestServiceApi } from '../../generated/openapi'; const config = new Configuration({ basePath: 'http://localhost:8080', }); // 工厂函数:批量创建带自定义axios实例的API对象 const createApi = <ApiClass extends new (...args: any[]) => any>(Api: ApiClass) => { return new Api(config, undefined, axiosClientNoAuth); }; // 使用示例 const hotelsApi = createApi(HotelsRestServiceApi); const anotherApi = createApi(AnotherRestServiceApi);
内容的提问来源于stack exchange,提问作者Villar
相关产品推荐
相关产品推荐

