1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- 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<AxiosResponse> => {
- 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<any>
- 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
|