巴青农资商城

apiAuth.js 1.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { getToken } from '@/utils/auth'
  2. import { PAGE_LOGIN } from '@/utils/pageRoute'
  3. const LOGIN_URL = PAGE_LOGIN
  4. /** 避免连续触发多次跳转登录页 */
  5. let loginRedirecting = false
  6. function redirectToLoginPage() {
  7. if (loginRedirecting) return
  8. loginRedirecting = true
  9. setTimeout(() => {
  10. loginRedirecting = false
  11. }, 2000)
  12. uni.navigateTo({
  13. url: LOGIN_URL,
  14. fail: () => {
  15. uni.reLaunch({ url: LOGIN_URL })
  16. }
  17. })
  18. }
  19. /**
  20. * 调用需登录的接口前校验 Token
  21. * @returns {boolean} 有 Token 返回 true,否则提示并跳转登录页
  22. */
  23. export function ensureApiToken(showToast = true) {
  24. if (getToken()) {
  25. return true
  26. }
  27. if (showToast) {
  28. uni.showToast({
  29. title: '请先登录',
  30. icon: 'none',
  31. duration: 1500
  32. })
  33. setTimeout(() => redirectToLoginPage(), 400)
  34. }
  35. return false
  36. }
  37. /**
  38. * 包装需登录的接口请求:无 Token 时直接 reject,不发起请求
  39. */
  40. export function callAuthApi(apiFn) {
  41. if (!ensureApiToken()) {
  42. return Promise.reject(new Error('未登录'))
  43. }
  44. return apiFn()
  45. }