1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| import 'reflect-metadata'; import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
declare type Constructor<T = any> = new (...args: any[]) => T declare type AxiosOptions = { config: AxiosRequestConfig; interceptors?: { request?: ((config: AxiosRequestConfig) => AxiosRequestConfig)[]; response?: ((resp: AxiosResponse) => AxiosResponse)[]; }; }
const Agents = (target: Constructor): Constructor => { return class extends target { constructor () { super(); const instances = Reflect.getMetadata('axios:instances', this) as string[] || []; instances.forEach((name) => { const options = Reflect.getMetadata('axios:options', this, name) as AxiosOptions; const instance = axios.create(options.config); if (options.interceptors?.request) { options.interceptors.request.forEach(c => instance.interceptors.request.use(c)); } if (options.interceptors?.response) { options.interceptors.response.forEach(c => instance.interceptors.response.use(c)); } Object.defineProperty(this, name, { value: instance }); }); } }; };
const Agent = (options: AxiosOptions): PropertyDecorator => (target, propertyKey) => { const instances = Reflect.getMetadata('axios:instances', target) as string[] || []; instances.push(propertyKey as string); Reflect.defineMetadata('axios:instances', instances, target); Reflect.defineMetadata('axios:options', options, target, propertyKey); };
@Agents class AxiosAgents { @Agent({ config: { baseURL: 'https://api.google.com/' } }) public google!: AxiosInstance;
@Agent({ config: { baseURL: 'https://api.baidu.com/' } }) public baidu!: AxiosInstance; }
export default new AxiosAgents();
|