鸿宇研学生前端代码
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.

105 lines
2.2 KiB

3 weeks ago
3 weeks ago
3 weeks ago
  1. import http from './http.js'
  2. import utils from '../utils/utils.js'
  3. let limit = {}
  4. let debounce = {}
  5. const models = ['login', 'index', 'image', 'activity', 'coupon', 'order', 'comment', 'bind', 'experience', 'partner', 'info']
  6. const config = {
  7. // 示例
  8. // wxLogin : {url : '/api/wxLogin', method : 'POST',
  9. // auth : false, showLoading : true, loadingTitle : '加载中...',
  10. // limit : 1000
  11. // },
  12. getConfig : {url : '/config/queryConfigList', method : 'GET', limit : 500},
  13. queryConfigByParamCode : {url : '/config/queryConfigByParamCode', method : 'GET'},
  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. utils.toLogin()
  41. console.error('需要登录', req.url)
  42. return Promise.reject()
  43. }
  44. }
  45. // 接口防抖
  46. if(req.debounce){
  47. let storageKey = req.url
  48. let storage = debounce[storageKey]
  49. if (storage) {
  50. clearTimeout(storage)
  51. }
  52. debounce[storageKey] = setTimeout(() => {
  53. clearTimeout(storage)
  54. delete debounce[storageKey]
  55. http.http(req.url, data, callback, req.method,
  56. loadingTitle || req.showLoading, loadingTitle || req.loadingTitle)
  57. }, req.debounce)
  58. return Promise.reject()
  59. }
  60. return http.http(req.url, data, callback, req.method,
  61. loadingTitle || req.showLoading, loadingTitle || req.loadingTitle)
  62. }
  63. function addApiModel(model, key){
  64. for(let k in model){
  65. if(config[`${k}`]){
  66. console.error(`重名api------model=${key},key=${k}`);
  67. uni.showModal({
  68. title: `重名api`,
  69. content: `model=${key},key=${k}`
  70. })
  71. continue
  72. }
  73. config[`${k}`] = model[k]
  74. // config[`${key}_${k}`] = model[k]
  75. }
  76. }
  77. models.forEach(key => {
  78. addApiModel(require(`./model/${key}.js`).default, key)
  79. })
  80. export default api