| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- import { getToken } from '@/utils/auth'
- import { getStoredLocale } from '@/utils/locale'
- import zh from '@/locale/zh'
- import bo from '@/locale/bo'
- const LOGIN_URL = '/pages/login/index'
- /** 避免连续触发多次跳转登录页 */
- let loginRedirecting = false
- function apiAuthMsg() {
- const locale = getStoredLocale()
- const pack = locale === 'bo' ? bo : zh
- return (pack.apiAuth && pack.apiAuth.needLogin) || '请先登录'
- }
- 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: apiAuthMsg(),
- icon: 'none',
- duration: 1500
- })
- setTimeout(() => redirectToLoginPage(), 400)
- }
- return false
- }
- /**
- * 包装需登录的接口请求:无 Token 时直接 reject,不发起请求
- */
- export function callAuthApi(apiFn) {
- if (!ensureApiToken()) {
- return Promise.reject(new Error('未登录'))
- }
- return apiFn()
- }
|