index.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import Axios, { AxiosResponse } from 'axios'
  2. import qs from 'querystring'
  3. import ProginnBridge from '../bridge'
  4. import { Notifier } from '../types/global'
  5. const factory = (opts: {
  6. baseURL?: string
  7. bridge?: ProginnBridge
  8. notifier?: Notifier
  9. withCredentials?: boolean
  10. defaultDataType?: 'json' | 'form' | false
  11. }) => {
  12. const {
  13. baseURL,
  14. notifier,
  15. bridge,
  16. withCredentials = true,
  17. defaultDataType = 'form'
  18. } = opts || {}
  19. const axios = Axios.create({
  20. baseURL,
  21. withCredentials
  22. })
  23. return async (opts: {
  24. method: 'GET' | 'POST'
  25. url: string
  26. query?: any
  27. data?: any
  28. dataType?: 'json' | 'form'
  29. headers?: any
  30. }): Promise<AxiosResponse> => {
  31. const {
  32. url,
  33. method,
  34. query,
  35. data,
  36. dataType = defaultDataType,
  37. headers = {}
  38. } = opts
  39. let contentType!: string
  40. let formattedData!: any
  41. if (dataType === 'form') {
  42. contentType = 'application/x-www-form-urlencoded'
  43. formattedData = data && qs.stringify(data)
  44. } else if (dataType === 'json') {
  45. contentType = 'application/json'
  46. formattedData = data && JSON.stringify(data)
  47. }
  48. if (method === 'POST' && contentType) {
  49. Object.assign(headers, {
  50. 'Content-Type': contentType
  51. })
  52. }
  53. let res: AxiosResponse<any>
  54. try {
  55. res = await axios({
  56. url,
  57. method,
  58. params: query,
  59. headers,
  60. data: formattedData
  61. })
  62. } catch (e) {
  63. notifier && notifier(e.message, e.status, e)
  64. return e
  65. }
  66. if (res.data) {
  67. const { status, data } = res.data
  68. // require login
  69. if (status === -99) {
  70. bridge && bridge.checkLogin(true)
  71. } else if (status !== 1 && status !== 200) {
  72. const message = data && data.message || res.data.message || res.data.info
  73. message && notifier && notifier(message, status, res)
  74. }
  75. }
  76. return res
  77. }
  78. }
  79. const ProginnRequest = {
  80. create: factory
  81. }
  82. export default ProginnRequest