201 lines
5.3 KiB
JavaScript
201 lines
5.3 KiB
JavaScript
import { getToken, logout, isSSOEnabled, getRefreshToken, setAuthTokens, isLoggedIn } from '@/utils/auth.js'
|
|
import { getGuestToken, clearGuestToken } from '@/utils/guest.js'
|
|
import { resolveBaseURL, getBaseURL } from '@/api/config.js'
|
|
|
|
export { getBaseURL }
|
|
|
|
function buildFullUrl(url) {
|
|
return resolveBaseURL().replace(/\/$/, '') + url
|
|
}
|
|
|
|
function refreshAccessToken() {
|
|
return new Promise((resolve, reject) => {
|
|
const refresh = getRefreshToken()
|
|
if (!refresh) {
|
|
reject(new Error('无刷新令牌'))
|
|
return
|
|
}
|
|
uni.request({
|
|
url: buildFullUrl('/auth/token'),
|
|
method: 'POST',
|
|
header: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
data: `grant_type=refresh_token&refresh_token=${encodeURIComponent(refresh)}&client_id=yz-uniapp`,
|
|
timeout: 10000,
|
|
success(res) {
|
|
const body = res.data || {}
|
|
if (res.statusCode === 200 && body.access_token) {
|
|
setAuthTokens(body)
|
|
resolve(body.access_token)
|
|
} else {
|
|
reject(new Error((body && (body.error || body.msg)) || '刷新失败'))
|
|
}
|
|
},
|
|
fail: reject
|
|
})
|
|
})
|
|
}
|
|
|
|
async function replayRequest(options) {
|
|
const token = await refreshAccessToken()
|
|
const res = await new Promise((resolve, reject) => {
|
|
uni.request({
|
|
url: buildFullUrl(options.url),
|
|
method: (options.method || 'GET').toUpperCase(),
|
|
data: options.data || {},
|
|
header: Object.assign(
|
|
{ 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
|
|
options.header || {}
|
|
),
|
|
timeout: options.timeout || 30000,
|
|
success: (r) => resolve(r.data || {}),
|
|
fail: reject
|
|
})
|
|
})
|
|
if (typeof res.code !== 'undefined' && res.code !== 200) {
|
|
const err = new Error(res.msg || '操作失败')
|
|
err.code = res.code
|
|
err.response = res
|
|
throw err
|
|
}
|
|
return typeof res.data !== 'undefined' ? res.data : res
|
|
}
|
|
|
|
export function request(options = {}) {
|
|
const { url, method = 'GET', data, header = {}, silent = false, timeout = 30000 } = options
|
|
const headers = {
|
|
'Content-Type': 'application/json',
|
|
...header
|
|
}
|
|
applyAuth(headers)
|
|
|
|
const fullUrl = buildFullUrl(url)
|
|
|
|
return new Promise((resolve, reject) => {
|
|
uni.request({
|
|
url: fullUrl,
|
|
method: method.toUpperCase(),
|
|
data: data || {},
|
|
header: headers,
|
|
timeout,
|
|
async success(res) {
|
|
const status = res.statusCode
|
|
const body = res.data || {}
|
|
|
|
if (status === 401 || body.code === 401) {
|
|
if (!isLoggedIn() && getGuestToken()) {
|
|
clearGuestToken()
|
|
if (!silent) {
|
|
uni.showToast({ title: '免登录授权已过期,请重新授权', icon: 'none' })
|
|
}
|
|
setTimeout(() => {
|
|
uni.reLaunch({ url: '/pages/nav/nav' })
|
|
}, 400)
|
|
reject(new Error(body.msg || '未授权'))
|
|
return
|
|
}
|
|
if (isSSOEnabled()) {
|
|
try {
|
|
resolve(await replayRequest(options))
|
|
return
|
|
} catch (e) {
|
|
}
|
|
}
|
|
logout()
|
|
if (!silent) {
|
|
uni.showToast({ title: body.msg || '请重新登录', icon: 'none' })
|
|
}
|
|
const onNav = (() => {
|
|
const ps = (typeof getCurrentPages === 'function' && getCurrentPages()) || []
|
|
const cur = ps.length ? ps[ps.length - 1] : null
|
|
if (!cur) return false
|
|
const route = cur.route || (cur.$page && cur.$page.path) || ''
|
|
return String(route).replace(/^\//, '') === 'pages/nav/nav'
|
|
})()
|
|
setTimeout(() => {
|
|
uni.reLaunch({ url: onNav ? '/pages/nav/nav' : '/pages/login/login' })
|
|
}, 400)
|
|
reject(new Error(body.msg || '未授权'))
|
|
return
|
|
}
|
|
|
|
if (status < 200 || status >= 300) {
|
|
const msg = body.msg || `请求失败(${status})`
|
|
if (!silent) uni.showToast({ title: msg, icon: 'none' })
|
|
const err = new Error(msg)
|
|
err.code = typeof body.code !== 'undefined' ? body.code : status
|
|
err.response = body
|
|
reject(err)
|
|
return
|
|
}
|
|
|
|
if (typeof body.code !== 'undefined' && body.code !== 200) {
|
|
const msg = body.msg || '操作失败'
|
|
if (!silent) uni.showToast({ title: msg, icon: 'none' })
|
|
const err = new Error(msg)
|
|
err.code = body.code
|
|
err.response = body
|
|
reject(err)
|
|
return
|
|
}
|
|
|
|
resolve(typeof body.data !== 'undefined' ? body.data : body)
|
|
},
|
|
fail(err) {
|
|
const detail = (err && err.errMsg) || ''
|
|
console.error('[request fail]', fullUrl, detail)
|
|
if (!silent) {
|
|
uni.showToast({
|
|
title: detail.includes('timeout') ? '请求超时' : '网络异常,请检查接口地址',
|
|
icon: 'none'
|
|
})
|
|
}
|
|
reject(new Error(detail || '网络异常'))
|
|
}
|
|
})
|
|
})
|
|
}
|
|
|
|
function applyAuth(headers) {
|
|
const token = getToken()
|
|
if (token) {
|
|
headers.Authorization = `Bearer ${token}`
|
|
return
|
|
}
|
|
const guestToken = getGuestToken()
|
|
if (guestToken) {
|
|
headers.Authorization = `Bearer ${guestToken}`
|
|
}
|
|
}
|
|
|
|
export function requestRaw(options = {}) {
|
|
const { url, method = 'GET', data, header = {} } = options
|
|
const headers = {
|
|
'Content-Type': 'application/json',
|
|
...header
|
|
}
|
|
applyAuth(headers)
|
|
|
|
const fullUrl = buildFullUrl(url)
|
|
|
|
return new Promise((resolve, reject) => {
|
|
uni.request({
|
|
url: fullUrl,
|
|
method: method.toUpperCase(),
|
|
data: data || {},
|
|
header: headers,
|
|
timeout: 30000,
|
|
success(res) {
|
|
resolve(res.data || {})
|
|
},
|
|
fail(err) {
|
|
console.error('[requestRaw fail]', fullUrl, err)
|
|
reject(err)
|
|
}
|
|
})
|
|
})
|
|
}
|
|
|
|
export function generateId() {
|
|
return `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`
|
|
}
|