index.ts 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. import axios, { AxiosRequestConfig, Method, AxiosInstance } from 'axios'
  2. //import qs from 'qs'
  3. //import cryptojs from 'crypto-js'
  4. //import { addPending, removePending } from './pending'
  5. import { useLoginStore } from '@/stores'
  6. import { HttpParams, CommonParams, HttpResponse, Payload, ResultCode } from './interface'
  7. import service from '@/services'
  8. const httpService = new (class {
  9. private axiosInstance?: AxiosInstance
  10. constructor() {
  11. this.init()
  12. }
  13. private init = async () => {
  14. if (!this.axiosInstance) {
  15. const config = await service.onReady()
  16. this.axiosInstance = axios.create({
  17. timeout: 30000,
  18. baseURL: config.goCommonSearchUrl,
  19. })
  20. // 请求拦截器
  21. this.axiosInstance.interceptors.request.use(
  22. (config) => {
  23. const { getToken } = useLoginStore()
  24. //removePending(config) //在请求开始前,对之前的请求做检查取消操作
  25. //addPending(config) //将当前请求添加到列表中
  26. //请求头签名
  27. const sign = {
  28. token: getToken(),
  29. signsecret: 'qz7qWOMXKTMT5JlDs5w4NTPwWeR3xhF1v6wqbZ9cExmP6cc3spvNAp1wJJ1SqRI5',
  30. timestamp: new Date().getTime(),
  31. }
  32. //设置请求头
  33. config.headers = {
  34. Authorization: sign.token,
  35. //Signid: 'eecd3f37625f4501b88e9f0fa14b4b51',
  36. //Sign: cryptojs.SHA256(qs.stringify(sign)).toString(),
  37. //Timestamp: sign.timestamp.toString(),
  38. }
  39. return config
  40. },
  41. (err) => {
  42. //此处异常触发条件不明
  43. console.error(err)
  44. return Promise.reject('网络异常,请稍后再试')
  45. }
  46. )
  47. // 响应拦截器
  48. this.axiosInstance.interceptors.response.use(
  49. (res) => {
  50. //removePending(res) //在请求结束后,移除本次请求
  51. return res
  52. },
  53. (err) => {
  54. const { msg, message } = err.response.data
  55. if (!axios.isCancel(err)) {
  56. console.error(err)
  57. }
  58. // 异常提示待优化
  59. return Promise.reject(msg || message || '服务器异常,请稍后再试')
  60. }
  61. )
  62. }
  63. return Promise.resolve(this.axiosInstance)
  64. }
  65. private request = async (url: string, method: Method, params?: unknown) => {
  66. const requestConfig: AxiosRequestConfig = {
  67. url,
  68. method,
  69. }
  70. if (params instanceof Object) {
  71. if (['post', 'POST', 'put', 'PUT', 'patch', 'PATCH'].includes(method)) {
  72. requestConfig.data = params
  73. } else {
  74. requestConfig.params = params
  75. }
  76. } else {
  77. requestConfig.url = url + (params ?? '')
  78. }
  79. const instance = await this.init()
  80. return instance(requestConfig)
  81. }
  82. commonRequest = async <T extends Payload>(url: string, method: Method, params: CommonParams<T>) => {
  83. const { data, success, fail, complete } = params
  84. await this.request(url, method, data).then((res) => {
  85. const data = res.data as T['rsp']
  86. success && success(data)
  87. }).catch((err) => {
  88. fail && fail(err)
  89. return Promise.reject(err)
  90. }).finally(() => {
  91. complete && complete()
  92. })
  93. }
  94. httpRequest = async <T extends Payload>(url: string, method: Method, params: HttpParams<T>) => {
  95. const { data, success, fail, complete } = params
  96. await this.request(url, method, data).then((res) => {
  97. const data = res.data as HttpResponse<T['rsp']>
  98. switch (data.code) {
  99. case ResultCode.InvalidToken:
  100. //退出登录
  101. //store.dispatch("user/logout", () => {
  102. // window.location.reload()
  103. //})
  104. return Promise.reject('令牌无效')
  105. case ResultCode.Success:
  106. success && success(data)
  107. return Promise.resolve()
  108. default:
  109. fail && fail(data.msg)
  110. return Promise.reject(data.msg)
  111. }
  112. }).catch((err) => {
  113. fail && fail(err)
  114. return Promise.reject(err)
  115. }).finally(() => {
  116. complete && complete()
  117. })
  118. }
  119. })
  120. export const { commonRequest, httpRequest } = httpService
  121. /**
  122. * 获取服务配置地址
  123. * @param key
  124. * @returns
  125. */
  126. export function getServiceUrl(key: keyof typeof service.config) {
  127. return service.config[key]
  128. }