推广小程序前端代码
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.

102 lines
2.1 KiB

7 months ago
7 months ago
7 months ago
5 months ago
7 months ago
5 months ago
7 months ago
7 months ago
5 months ago
7 months ago
5 months ago
7 months ago
5 months ago
7 months 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', 'vip', 'info', 'order','zhaomu']
  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_common/getConfig', method : 'GET', limit : 500},
  13. }
  14. export function api(key, data, callback, loadingTitle) {
  15. let req = config[key]
  16. if (!req) {
  17. console.error('无效key--------' + key);
  18. return Promise.reject('无效key--------' + key)
  19. }
  20. if (typeof callback == 'string') {
  21. loadingTitle = callback
  22. }
  23. if (typeof data == 'function') {
  24. callback = data
  25. data = {}
  26. }
  27. // 接口限流
  28. if (req.limit) {
  29. let storageKey = req.url
  30. let storage = limit[storageKey]
  31. if (storage && new Date().getTime() - storage < req.limit) {
  32. return Promise.reject('接口限流', key)
  33. }
  34. limit[storageKey] = new Date().getTime()
  35. }
  36. //必须登录
  37. if (req.auth) {
  38. if (!uni.getStorageSync('token')) {
  39. utils.toLogin()
  40. store.state.userInfo = {}
  41. store.state.token = ""
  42. uni.removeStorageSync('token')
  43. console.error('需要登录')
  44. return Promise.reject('必须登录')
  45. }
  46. }
  47. // 接口防抖
  48. if(req.debounce){
  49. let storageKey = req.url
  50. let storage = debounce[storageKey]
  51. if (storage) {
  52. clearTimeout(storage)
  53. }
  54. debounce[storageKey] = setTimeout(() => {
  55. clearTimeout(storage)
  56. delete debounce[storageKey]
  57. http.http(req.url, data, callback, req.method,
  58. loadingTitle || req.showLoading, loadingTitle || req.loadingTitle)
  59. }, req.debounce)
  60. return Promise.reject('接口防抖', key)
  61. }
  62. return http.http(req.url, data, callback, req.method,
  63. loadingTitle || req.showLoading, loadingTitle || req.loadingTitle)
  64. }
  65. function addApiModel(model, key){
  66. for(let k in model){
  67. if(config[`${k}`]){
  68. console.error(`重名api------model=${key},key=${k}`);
  69. continue
  70. }
  71. config[`${k}`] = model[k]
  72. // config[`${key}_${k}`] = model[k]
  73. }
  74. }
  75. models.forEach(key => {
  76. addApiModel(require(`./model/${key}.js`).default, key)
  77. })
  78. export default api