爱简收旧衣按件回收前端代码仓库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

99 lines
2.2 KiB

1 week ago
3 weeks ago
1 week ago
3 weeks ago
1 week ago
1 week ago
1 week ago
3 weeks ago
  1. // api/index.js
  2. import http from './http.js'
  3. import utils from '../utils/utils.js'
  4. import config from './config.js'
  5. const limit = new Map()
  6. const debounce = new Map()
  7. // 动态导入 models
  8. const modules = import.meta.glob('./model/*.js', { eager: true })
  9. Object.entries(modules).forEach(([path, mod]) => {
  10. const model = mod.default || mod
  11. const key = path.match(/\/([^/]+)\.js$/)[1]
  12. for (const k in model) {
  13. if (config[k]) {
  14. console.error(`重名api------model=${key},key=${k}`)
  15. // 这里建议用全局弹窗或通知
  16. continue
  17. }
  18. config[k] = model[k]
  19. }
  20. })
  21. /**
  22. * 通用API请求
  23. * @param {string} key
  24. * @param {object} data
  25. * @param {function} [callback]
  26. * @param {string} [loadingTitle]
  27. * @returns {Promise}
  28. */
  29. export function api(key, data = {}, callback, loadingTitle) {
  30. const req = config[key]
  31. if (!req) {
  32. console.error('无效key: ' + key)
  33. return Promise.reject(new Error('无效key'))
  34. }
  35. // 参数重载
  36. if (typeof callback === 'string') {
  37. loadingTitle = callback
  38. callback = undefined
  39. }
  40. if (typeof data === 'function') {
  41. callback = data
  42. data = {}
  43. }
  44. // 限流
  45. if (req.limit) {
  46. const last = limit.get(req.url)
  47. if (last && Date.now() - last < req.limit) {
  48. return Promise.reject(new Error('请求过于频繁'))
  49. }
  50. limit.set(req.url, Date.now())
  51. }
  52. // console.log(!uni.getStorageSync('token'),'status');
  53. // 必须登录
  54. if (req.auth && !uni.getStorageSync('token')) {
  55. // utils.toLogin()
  56. return Promise.reject(new Error('需要登录'))
  57. }
  58. // 防抖
  59. if (req.debounce) {
  60. const prev = debounce.get(req.url)
  61. if (prev) clearTimeout(prev)
  62. debounce.set(
  63. req.url,
  64. setTimeout(() => {
  65. debounce.delete(req.url)
  66. http.http(
  67. req.url,
  68. data,
  69. callback,
  70. req.method,
  71. loadingTitle || req.showLoading,
  72. loadingTitle || req.loadingTitle
  73. )
  74. }, req.debounce)
  75. )
  76. return Promise.reject(new Error('请求防抖中'))
  77. }
  78. // 正常请求
  79. return http.http(
  80. req.url,
  81. data,
  82. callback,
  83. req.method,
  84. loadingTitle || req.showLoading,
  85. loadingTitle || req.loadingTitle
  86. )
  87. }
  88. export default api