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

114 lines
2.3 KiB

3 months ago
3 months ago
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', 'my_book', 'comment', 'task'
  6. , 'order', 'writer', 'achievement']
  7. const config = {
  8. // 示例
  9. // wxLogin : {url : '/api/wxLogin', method : 'POST',
  10. // auth : false, showLoading : true, loadingTitle : '加载中...',
  11. // limit : 1000
  12. // },
  13. // 获取平台基础配置信息
  14. getConfig: {
  15. url: '/all_login/getConfig',
  16. method: 'GET',
  17. },
  18. }
  19. export function api(key, data, callback, loadingTitle) {
  20. let req = config[key]
  21. if (!req) {
  22. console.error('无效key' + key);
  23. return Promise.reject()
  24. }
  25. if (typeof callback == 'string') {
  26. loadingTitle = callback
  27. }
  28. if (typeof data == 'function') {
  29. callback = data
  30. data = {}
  31. }
  32. // 接口限流
  33. if (req.limit) {
  34. let storageKey = req.url
  35. let storage = limit[storageKey]
  36. if (storage && new Date().getTime() - storage < req.limit) {
  37. return Promise.reject()
  38. }
  39. limit[storageKey] = new Date().getTime()
  40. }
  41. //必须登录
  42. if (req.auth) {
  43. if (!uni.getStorageSync('token')) {
  44. // utils.toLogin()
  45. // console.error('需要登录', req.url)
  46. // store.commit('logout', '登录过期了,你可以停留在此页面或去重新登录')
  47. console.error('登录过期');
  48. utils.toLogin()
  49. return Promise.reject()
  50. }
  51. }
  52. // 接口防抖
  53. if(req.debounce){
  54. let storageKey = req.url
  55. let storage = debounce[storageKey]
  56. if (storage) {
  57. clearTimeout(storage)
  58. }
  59. debounce[storageKey] = setTimeout(() => {
  60. clearTimeout(storage)
  61. delete debounce[storageKey]
  62. http.http(req.url, data, callback, req.method,
  63. loadingTitle || req.showLoading, loadingTitle || req.loadingTitle)
  64. }, req.debounce)
  65. return Promise.reject()
  66. }
  67. return http.http(req.url, data, callback, req.method,
  68. loadingTitle || req.showLoading, loadingTitle || req.loadingTitle)
  69. }
  70. function addApiModel(model, key){
  71. for(let k in model){
  72. if(config[`${k}`]){
  73. console.error(`重名api------model=${key},key=${k}`);
  74. uni.showModal({
  75. title: `重名api`,
  76. content: `model=${key},key=${k}`
  77. })
  78. continue
  79. }
  80. config[`${k}`] = model[k]
  81. // config[`${key}_${k}`] = model[k]
  82. }
  83. }
  84. models.forEach(key => {
  85. addApiModel(require(`./model/${key}.js`).default, key)
  86. })
  87. export default api