建材商城系统20241014
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.

110 lines
2.2 KiB

7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
  1. import http from './http.js'
  2. import utils from '../utils/utils.js'
  3. import store from '../store/store.js'
  4. let limit = {}
  5. let debounce = {}
  6. const models = ['login', 'index', 'cart']
  7. const config = {
  8. // 示例
  9. // wxLogin : {url : '/api/wxLogin', method : 'POST',
  10. // auth : false, showLoading : true, loadingTitle : '加载中...',
  11. // limit : 1000
  12. // },
  13. getConfig : {url : '/conf/getConfig', method : 'GET', limit : 500},
  14. }
  15. export function api(key, data, callback, loadingTitle) {
  16. let req = config[key]
  17. if (!req) {
  18. console.error('无效key' + key);
  19. return Promise.reject()
  20. }
  21. if (typeof callback == 'string') {
  22. loadingTitle = callback
  23. }
  24. if (typeof data == 'function') {
  25. callback = data
  26. data = {}
  27. }
  28. // 接口限流
  29. if (req.limit) {
  30. let storageKey = req.url
  31. let storage = limit[storageKey]
  32. if (storage && new Date().getTime() - storage < req.limit) {
  33. return Promise.reject()
  34. }
  35. limit[storageKey] = new Date().getTime()
  36. }
  37. //必须登录
  38. if (req.auth) {
  39. if (!uni.getStorageSync('token')) {
  40. store.state.userInfo = {}
  41. store.state.riceInfo = {}
  42. uni.removeStorageSync('token')
  43. utils.toLogin()
  44. console.error('需要登录', req.url)
  45. return Promise.reject()
  46. }
  47. }
  48. // 接口防抖
  49. if(req.debounce){
  50. let storageKey = req.url
  51. let storage = debounce[storageKey]
  52. if (storage) {
  53. clearTimeout(storage)
  54. }
  55. debounce[storageKey] = setTimeout(() => {
  56. clearTimeout(storage)
  57. delete debounce[storageKey]
  58. http.http(req.url, data, callback, req.method,
  59. loadingTitle || req.showLoading, loadingTitle || req.loadingTitle)
  60. }, req.debounce)
  61. return Promise.reject()
  62. }
  63. return http.http(req.url, data, callback, req.method,
  64. loadingTitle || req.showLoading, loadingTitle || req.loadingTitle)
  65. }
  66. function addApiModel(model, key){
  67. for(let k in model){
  68. if(config[`${k}`]){
  69. console.error(`重名api------model=${key},key=${k}`);
  70. uni.showModal({
  71. title: `重名api`,
  72. content: `model=${key},key=${k}`
  73. })
  74. continue
  75. }
  76. config[`${k}`] = model[k]
  77. // config[`${key}_${k}`] = model[k]
  78. }
  79. }
  80. models.forEach(key => {
  81. addApiModel(require(`./model/${key}.js`).default, key)
  82. })
  83. export default api