index.ts 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. import axios from 'axios'
  2. import plus from '@/utils/h5plus'
  3. export default new (class {
  4. /** 服务配置信息 */
  5. config = {
  6. commSearchUrl: '',
  7. goCommonSearchUrl: '',
  8. hsbyBankSignZone: '',
  9. hsbyRegister: '',
  10. hsbyPayUrlWeb: '',
  11. hsbySignUp: '',
  12. mobileAuthUrl: '',
  13. mobileOpenUrl: '',
  14. newsUrl: '',
  15. openApiUrl: '',
  16. quoteHost: '',
  17. quotePort: '',
  18. quoteUrl: '',
  19. tradeHost: '',
  20. tradePort: '',
  21. tradeUrl: '',
  22. uploadUrl: '',
  23. oem: '',
  24. iOS: '',
  25. android: '',
  26. androidUpdateUrl: '',
  27. pcNewsUrl: '',
  28. pcMangerUrl: '',
  29. shareUrl: '',
  30. }
  31. /** 服务初始化完成状态 */
  32. isReady = false
  33. /** 等待服务初始化 */
  34. private isPending = false
  35. /**
  36. * 自动初始化,若断网或其它原因导致初始化失败,需手动初始化
  37. * IOS上架审核可能会遇到网络权限的情况,应用可能会在未授权网络权限的情况下发起请求,导致请求等待时间过长,最终审核被拒
  38. */
  39. //private onload = this.init()
  40. /**
  41. * 手动初始化
  42. */
  43. private onload = Promise.resolve(this.config)
  44. /**
  45. * 重试次数
  46. */
  47. private retryCount = 0
  48. /**
  49. * 失败时重新尝试初始化,直到成功为止
  50. */
  51. private tryinit = () => {
  52. return new Promise<typeof this.config>((resolve, reject) => {
  53. if (this.retryCount >= 5) {
  54. this.retryCount = 0
  55. this.isPending = false
  56. reject('服务加载失败,请稍后再试')
  57. } else {
  58. this.retryCount++
  59. // 自动计算每次重试的延时,重试次数越多,延时越大
  60. // const delay = this.retryCount * 3000
  61. setTimeout(() => {
  62. resolve(this.init())
  63. }, 3000)
  64. }
  65. })
  66. }
  67. /**
  68. * 初始化服务配置
  69. * https://uniapp.dcloud.net.cn/tutorial/app-ios-uiwebview.html
  70. */
  71. private init(): Promise<typeof this.config> {
  72. this.isPending = true
  73. return new Promise((resolve, reject) => {
  74. const filePath = './config/appconfig.json'
  75. const getAppConfig = async () => {
  76. if (plus.hasPlus()) {
  77. const res = await plus.getLocalFileContent(filePath)
  78. return JSON.parse(res)
  79. } else {
  80. const res = await axios(filePath)
  81. return res.data
  82. }
  83. }
  84. getAppConfig().then((res) => {
  85. // 获取服务接口地址
  86. axios(res.apiUrl).then((res) => {
  87. this.config = res.data.data
  88. this.isReady = true
  89. resolve(this.config)
  90. }).catch(() => {
  91. const result = this.tryinit()
  92. resolve(result)
  93. })
  94. }).catch(() => {
  95. reject('配置文件加载失败,请稍后再试')
  96. })
  97. })
  98. }
  99. /**
  100. * 服务初始化完成时触发
  101. */
  102. onReady() {
  103. if (!this.isReady && !this.isPending) {
  104. this.onload = this.init()
  105. }
  106. // 确保当前只有一个初始化实例
  107. return this.onload
  108. }
  109. })