import axiosInstance from './axiosInstance' import { Method, AxiosRequestConfig } from 'axios' import { defaultVersion, defaultService } from 'src/config' class MainApi { private readonly action: string private readonly method: Method private readonly service: string private readonly version: string private defaultParams: any = {} constructor ( action: string, method: Method, service: string = defaultService, version: string = defaultVersion ) { this.action = action this.method = method this.service = service this.version = version } private _generateConfig (params?: P, formType: boolean = false): AxiosRequestConfig { const requestConfig: AxiosRequestConfig = { method: this.method } const urlParam = { Action: this.action, Service: this.service, Version: this.version } requestConfig.params = urlParam if (Array.isArray(params)) { requestConfig.data = params return requestConfig } if (this.method === 'get') requestConfig.params = Object.assign(urlParam, params, this.defaultParams) else if (this.method === 'post') { const param = Object.assign(params, this.defaultParams) requestConfig.data = formType ? new URLSearchParams(param as unknown as Record) : param } return requestConfig } setDefaultParams (p: any): this { this.defaultParams = p return this } async apiRequest (params?: P, formType: boolean = true): Promise { return new Promise((resolve, reject) => { const config = this._generateConfig(params, formType) axiosInstance.request(config) .then(res => resolve(res.data)) .catch(e => reject(e)) }) } async consoleRequest (params?: P): Promise { return new Promise((resolve, reject) => { const config = this._generateConfig(params) axiosInstance.request(config) .then(res => { resolve(res.data.data ?? res.data) }) .catch(e => reject(e.error)) }) } } export default KeadApi