西藏巴青项目

apiAuth.js 1.0KB

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