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

2 months ago
2 months ago
2 months ago
3 weeks ago
2 months ago
3 weeks ago
2 months ago
3 weeks ago
2 months ago
3 weeks ago
2 months ago
3 weeks ago
2 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. console.error('需要登录')
  41. return Promise.reject('必须登录')
  42. }
  43. }
  44. // 接口防抖
  45. if(req.debounce){
  46. let storageKey = req.url
  47. let storage = debounce[storageKey]
  48. if (storage) {
  49. clearTimeout(storage)
  50. }
  51. debounce[storageKey] = setTimeout(() => {
  52. clearTimeout(storage)
  53. delete debounce[storageKey]
  54. http.http(req.url, data, callback, req.method,
  55. loadingTitle || req.showLoading, loadingTitle || req.loadingTitle)
  56. }, req.debounce)
  57. return Promise.reject('接口防抖', key)
  58. }
  59. return http.http(req.url, data, callback, req.method,
  60. loadingTitle || req.showLoading, loadingTitle || req.loadingTitle)
  61. }
  62. function addApiModel(model, key){
  63. for(let k in model){
  64. if(config[`${k}`]){
  65. console.error(`重名api------model=${key},key=${k}`);
  66. continue
  67. }
  68. config[`${k}`] = model[k]
  69. // config[`${key}_${k}`] = model[k]
  70. }
  71. }
  72. models.forEach(key => {
  73. addApiModel(require(`./model/${key}.js`).default, key)
  74. })
  75. export default api