export interface AxiosConfig {
BASEURL: {
host: string
port: number
path?: string
}
}
interface InstanceMap {
[key: string]: AxiosInstance | null
}
const instanceMap: InstanceMap = {
base: null, // 当前系统ip下的请求
business: null, // 后台接口请求
}
// 初始化默认实例
export const initAxiosInstance = (config: AxiosConfig) => {
if (!config) return
const {
BASEURL: { host, port },
} = config
const BASEURL = `//${host || location.hostname}:${port}/`
instanceMap.base = new Http({
BASEURL: BASEURL,
errorHandler,
}).instance
}
// 初始化后台实例
export const initBusinessInstance = (config: AxiosConfig) => {
if (!config) return
const {
BASEURL: { host, port, path },
} = config
const BASEURL = `//${host || location.hostname}:${port}/${path}`
instanceMap.business = new Http({
BASEURL: BASEURL,
errorHandler,
}).instance
// set auth headers
instanceMap.business.defaults.headers.common['Authorization'] = `${getToken()}`
}
// 业务方法 GET
export const GET = <T>(
url: string,
serviceName?: string,
params?: Record<string, any>,
options?: Record<string, any>
): Promise<T> => {
if (!instanceMap.base) {
throw new Error('instanceMap.base is null')
}
return get<T>(instanceMap.base, url, serviceName, params, options)
}
// 业务方法 POST
export const POST = <T>(
url: string,
serviceName?: string,
data?: Record<string, any>,
options?: Record<string, any>
): Promise<T> => {
if (!instanceMap.base) {
throw new Error('instanceMap.base is null')
}
return post<T>(instanceMap.base, url, serviceName, data, options)
}
// 业务方法 PUT
export const PUT = <T>(
url: string,
serviceName?: string,
data?: Record<string, any>,
options?: Record<string, any>
): Promise<T> => {
if (!instanceMap.base) {
throw new Error('instanceMap.base is null')
}
return put<T>(instanceMap.base, url, serviceName, data, options)
}
// 业务方法 DELETE
export const DELETE = <T>(
url: string,
serviceName?: string,
data?: Record<string, any>,
options?: Record<string, any>
): Promise<T> => {
if (!instanceMap.base) {
throw new Error('instanceMap.base is null')
}
return del<T>(instanceMap.base, url, serviceName, data, options)
}
// 业务方法 HEAD
export const HEAD = <T>(
url: string,
serviceName?: string,
params?: Record<string, any>,
options?: Record<string, any>
): Promise<T> => {
if (!instanceMap.base) {
throw new Error('instanceMap.base is null')
}
return head<T>(instanceMap.base, url, serviceName, params, options)
}