| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- import { getToken } from '@/utils/auth'
- import { PAGE_LOGIN } from '@/utils/pageRoute'
- const LOGIN_URL = PAGE_LOGIN
- /** 避免连续触发多次跳转登录页 */
- let loginRedirecting = false
- function redirectToLoginPage() {
- if (loginRedirecting) return
- loginRedirecting = true
- setTimeout(() => {
- loginRedirecting = false
- }, 2000)
- uni.navigateTo({
- url: LOGIN_URL,
- fail: () => {
- uni.reLaunch({ url: LOGIN_URL })
- }
- })
- }
- /**
- * 调用需登录的接口前校验 Token
- * @returns {boolean} 有 Token 返回 true,否则提示并跳转登录页
- */
- export function ensureApiToken(showToast = true) {
- if (getToken()) {
- return true
- }
- if (showToast) {
- uni.showToast({
- title: '请先登录',
- icon: 'none',
- duration: 1500
- })
- setTimeout(() => redirectToLoginPage(), 400)
- }
- return false
- }
- /**
- * 包装需登录的接口请求:无 Token 时直接 reject,不发起请求
- */
- export function callAuthApi(apiFn) {
- if (!ensureApiToken()) {
- return Promise.reject(new Error('未登录'))
- }
- return apiFn()
- }
|