import Axios, { AxiosResponse } from 'axios' import qs from 'querystring' import ProginnBridge from '../bridge' import { Notifier } from '../types/global' const factory = (opts: { baseURL?: string bridge?: ProginnBridge notifier?: Notifier withCredentials?: boolean defaultDataType?: 'json' | 'form' | false }) => { const { baseURL, notifier, bridge, withCredentials = true, defaultDataType = 'form' } = opts || {} const axios = Axios.create({ baseURL, withCredentials }) return async (opts: { method: 'GET' | 'POST' url: string query?: any data?: any dataType?: 'json' | 'form' headers?: any }): Promise => { const { url, method, query, data, dataType = defaultDataType, headers = {} } = opts let contentType!: string let formattedData!: any if (dataType === 'form') { contentType = 'application/x-www-form-urlencoded' formattedData = data && qs.stringify(data) } else if (dataType === 'json') { contentType = 'application/json' formattedData = data && JSON.stringify(data) } if (method === 'POST' && contentType) { Object.assign(headers, { 'Content-Type': contentType }) } let res: AxiosResponse try { res = await axios({ url, method, params: query, headers, data: formattedData }) } catch (e) { notifier && notifier(e.message, e.status, e) return e } if (res.data) { const { status, data } = res.data // require login if (status === -99) { bridge && bridge.checkLogin(true) } else if (status !== 1 && status !== 200) { const message = data && data.message || res.data.message || res.data.info message && notifier && notifier(message, status, res) } } return res } } const ProginnRequest = { create: factory } export default ProginnRequest