index.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import { Method, HttpConfig, HttpRequest, HttpResponse, ResultCode } from './interface'
  2. import { addPending, removePending } from './pending/index'
  3. /**
  4. * 根据url参数生成唯一key
  5. */
  6. function getRequestKey<T>(config: HttpConfig<T>) {
  7. const { method, url, data } = config
  8. const requestKey: string[] = [method, url]
  9. if (data) {
  10. // 参数转换查询字符串
  11. const queryString = Object.entries(data).reduce((res, property, index) => {
  12. const str = property[0] + '=' + property[1]
  13. return index > 0 ? res + '&' + str : str
  14. }, '')
  15. requestKey.push(queryString)
  16. }
  17. return requestKey.join('&')
  18. }
  19. /**
  20. * Http请求
  21. */
  22. function httpMiddleware<T>(config: HttpConfig<T>) {
  23. const { url, method, enableAuthorization, data } = config
  24. // 过滤字符串前面所有 '/' 字符
  25. const requestUrl = url.replace(/^\/+/, '')
  26. // 请求头
  27. const header = {
  28. 'Authorization': wx.getStorageSync('Authorization'),
  29. 'Group': 5,
  30. 'LoginID': wx.getStorageSync('LoginID')
  31. }
  32. return new Promise((resolve, reject) => {
  33. const requestKey = getRequestKey(config)
  34. // 在请求开始前,对之前的请求做检查取消操作
  35. removePending(requestKey)
  36. const requestTask = wx.request({
  37. url: requestUrl,
  38. method,
  39. header: enableAuthorization ? header : {},
  40. data: data ?? {},
  41. success: (res) => {
  42. resolve(res.data)
  43. },
  44. fail: (err) => {
  45. reject('请求异常,请稍后再试'+err)
  46. },
  47. complete: () => {
  48. // 在请求结束后,移除本次请求
  49. removePending(requestKey)
  50. }
  51. })
  52. // 将当前请求添加到列表中
  53. addPending(requestKey, requestTask)
  54. })
  55. }
  56. /**
  57. * Http请求结果
  58. */
  59. export async function httpRequest<T extends { req?: unknown, rsp?: unknown }>(url: string, method: Method, params: HttpRequest<T>): Promise<void> {
  60. const { data, enableAuthorization, success, fail, complete } = params;
  61. const config: HttpConfig<T['req']> = {
  62. url,
  63. method,
  64. enableAuthorization: enableAuthorization ?? true,
  65. data,
  66. }
  67. await httpMiddleware(config).then((res) => {
  68. const data = res as HttpResponse<T['rsp']>
  69. switch (data.code) {
  70. case ResultCode.InvalidToken:
  71. // 退出登录
  72. // logout();
  73. return Promise.reject('令牌无效')
  74. case ResultCode.Success:
  75. success && success(data)
  76. return Promise.resolve()
  77. case ResultCode.Code:
  78. success && success(data)
  79. return Promise.resolve()
  80. default:
  81. return Promise.reject(data.msg)
  82. }
  83. }).catch((err) => {
  84. fail && fail(err);
  85. return Promise.reject(err);
  86. }).finally(() => {
  87. complete && complete()
  88. })
  89. }