axios-pluginify
Version:
`axios-pluginify` 是一款极小的工具, 可以让 `axios` 成为基于插件的请求库.
64 lines • 2.17 kB
JavaScript
export * from './plugins';
export function definePlugin(plugin) {
return function pluginWrapper(...args) {
if (typeof plugin.apply === 'function') {
plugin.apply.apply(this, args);
}
if (plugin.beforeCreate) {
this.beforeCreate = plugin.beforeCreate.bind(this);
}
if (plugin.created) {
this.created = plugin.created.bind(this);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
};
}
class AxiosPluginify {
constructor(axiosStatic, config) {
this.axiosStatic = axiosStatic;
this.config = config;
this.beforeCreate = [];
this.created = [];
}
use(...plugins) {
for (const plugin of plugins) {
if (typeof plugin.beforeCreate === 'function') {
this.beforeCreate.push((config, axios) =>
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
plugin.beforeCreate(config, axios));
}
if (typeof plugin.created === 'function') {
this.created.push((axios, config) =>
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
plugin.created(axios, config));
}
}
return this;
}
generate(destroy = false) {
for (const hook of this.beforeCreate) {
hook(this.config, this.axiosStatic);
}
const axios = this.axiosStatic.create(this.config);
for (const hook of this.created) {
hook(axios, this.config);
}
if (destroy) {
this.destroy();
}
return axios;
}
destroy() {
this.beforeCreate = [];
this.created = [];
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
this.config = this.axiosStatic = null;
}
}
export function pluginify(axiosStatic, config = {}) {
return new AxiosPluginify(axiosStatic, config);
}
//# sourceMappingURL=index.js.map