http.ts 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. import { refreshToken } from '../core/libs/requests'
  2. import { CustomRequestOptions } from '../interceptors/request'
  3. import { useUserStore } from '../store'
  4. import dayjs from 'dayjs'
  5. const userStore = useUserStore()
  6. console.log(userStore.userInfo)
  7. const Authorization = userStore.userInfo?.token
  8. console.log(Authorization)
  9. const header: { 'tenant-id': number; Authorization?: string } = {
  10. 'tenant-id': 1,
  11. }
  12. Authorization && (header.Authorization = `Bearer ${Authorization}`)
  13. export const http = async <T>(options: CustomRequestOptions) => {
  14. const userStore = useUserStore()
  15. // console.log(dayjs(userStore.userInfo.expiresTime).format('YYYY-MM-DD HH:mm:ss'))
  16. const diff = dayjs(userStore.userInfo.expiresTime).diff(dayjs(), 'minutes')
  17. // console.log(diff)
  18. if (userStore.isLogined && diff < 10 && options.url !== '/app-api/member/auth/refresh-token') {
  19. const { data } = await refreshToken(userStore.userInfo.refreshToken)
  20. userStore.setUserInfo({
  21. ...userStore.userInfo,
  22. token: data.accessToken,
  23. userId: data.userId,
  24. accessToken: data.accessToken,
  25. refreshToken: data.refreshToken,
  26. expiresTime: data.expiresTime,
  27. // openid: data.openid,
  28. })
  29. }
  30. // 1. 返回 Promise 对象
  31. return new Promise<IResData<T>>((resolve, reject) => {
  32. uni.request({
  33. ...options,
  34. header,
  35. dataType: 'json',
  36. // #ifndef MP-WEIXIN
  37. responseType: 'json',
  38. // #endif
  39. // 响应成功
  40. success(res) {
  41. // console.log(res)
  42. // 状态码 2xx,参考 axios 的设计
  43. if (res.statusCode >= 200 && res.statusCode < 300) {
  44. // 2.1 提取核心数据 res.data
  45. if ((res.data as IResData<T>).code === 0) {
  46. resolve(res.data as IResData<T>)
  47. } else if ((res.data as IResData<T>).code === 401) {
  48. userStore.clearUserInfo()
  49. uni.navigateTo({ url: '/pages/login/index' })
  50. reject(res)
  51. } else {
  52. !options.hideErrorToast &&
  53. uni.showToast({
  54. icon: 'none',
  55. title: (res.data as IResData<T>).msg || '请求错误',
  56. })
  57. reject(res)
  58. }
  59. } else if (res.statusCode === 401) {
  60. // 401错误 -> 清理用户信息,跳转到登录页
  61. userStore.clearUserInfo()
  62. reject(res)
  63. } else {
  64. // 其他错误 -> 根据后端错误信息轻提示
  65. !options.hideErrorToast &&
  66. uni.showToast({
  67. icon: 'none',
  68. title: (res.data as IResData<T>).msg || '请求错误',
  69. })
  70. reject(res)
  71. }
  72. },
  73. // 响应失败
  74. fail(err) {
  75. uni.showToast({
  76. icon: 'none',
  77. title: '网络错误,换个网络试试',
  78. })
  79. reject(err)
  80. },
  81. })
  82. })
  83. }
  84. /**
  85. * GET 请求
  86. * @param url 后台地址
  87. * @param query 请求query参数
  88. * @returns
  89. */
  90. export const httpGet = <T>(url: string, query?: Record<string, any>) => {
  91. return http<T>({
  92. url,
  93. query,
  94. method: 'GET',
  95. })
  96. }
  97. /**
  98. * POST 请求
  99. * @param url 后台地址
  100. * @param data 请求body参数
  101. * @param query 请求query参数,post请求也支持query,很多微信接口都需要
  102. * @returns
  103. */
  104. export const httpPost = <T>(
  105. url: string,
  106. data?: Record<string, any>,
  107. query?: Record<string, any>,
  108. ) => {
  109. return http<T>({
  110. url,
  111. query,
  112. data,
  113. method: 'POST',
  114. })
  115. }
  116. export const httpPut = <T>(url: string, data?: Record<string, any>) =>
  117. http<T>({
  118. url,
  119. query: {},
  120. data,
  121. method: 'PUT',
  122. })
  123. http.get = httpGet
  124. http.post = httpPost