小说小程序前端代码仓库(小程序)
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.

108 lines
2.1 KiB

3 months ago
3 months ago
3 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', 'bookshelf']
  6. const config = {
  7. // 示例
  8. // wxLogin : {url : '/api/wxLogin', method : 'POST',
  9. // auth : false, showLoading : true, loadingTitle : '加载中...',
  10. // limit : 1000
  11. // },
  12. // 获取平台基础配置信息
  13. getConfig: {
  14. url: '/all_login/getConfig',
  15. method: 'GET',
  16. },
  17. }
  18. export function api(key, data, callback, loadingTitle) {
  19. let req = config[key]
  20. if (!req) {
  21. console.error('无效key' + key);
  22. return Promise.reject()
  23. }
  24. if (typeof callback == 'string') {
  25. loadingTitle = callback
  26. }
  27. if (typeof data == 'function') {
  28. callback = data
  29. data = {}
  30. }
  31. // 接口限流
  32. if (req.limit) {
  33. let storageKey = req.url
  34. let storage = limit[storageKey]
  35. if (storage && new Date().getTime() - storage < req.limit) {
  36. return Promise.reject()
  37. }
  38. limit[storageKey] = new Date().getTime()
  39. }
  40. //必须登录
  41. if (req.auth) {
  42. if (!uni.getStorageSync('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