248 lines
5.8 KiB
JavaScript
248 lines
5.8 KiB
JavaScript
const auth = require('./auth')
|
|||
|
|
const { API_BASE_URL, REQUEST_TIMEOUT } = require('./config')
|
||
|
|
|
||
|
|
let isRefreshing = false
|
||
|
|
let requestQueue = []
|
||
|
|
let redirectingToAuth = false
|
||
|
|
|
||
|
|
function buildRequestUrl(url, params) {
|
||
|
|
const query = Object.keys(params || {})
|
||
|
|
.filter(key => params[key] !== undefined && params[key] !== null && params[key] !== '')
|
||
|
|
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
|
||
|
|
.join('&')
|
||
|
|
|
||
|
|
const target = `${API_BASE_URL}${url}`
|
||
|
|
return query ? `${target}${target.includes('?') ? '&' : '?'}${query}` : target
|
||
|
|
}
|
||
|
|
|
||
|
|
function isWhitelistedPath(url) {
|
||
|
|
return [
|
||
|
|
'/user/login',
|
||
|
|
'/user/register',
|
||
|
|
'/user/check/',
|
||
|
|
'/user/refresh-token',
|
||
|
|
'/user/send-verification-code',
|
||
|
|
'/user/phone-login',
|
||
|
|
'/user/reset-password-by-phone',
|
||
|
|
'/product/get/',
|
||
|
|
'/product/list/',
|
||
|
|
'/shop/get/',
|
||
|
|
'/shop/list/public',
|
||
|
|
'/shop/list/simple',
|
||
|
|
'/tag/list/all',
|
||
|
|
'/file/get-signed-url/'
|
||
|
|
].some(path => String(url || '').includes(path))
|
||
|
|
}
|
||
|
|
|
||
|
|
function normalizeError(message, statusCode, raw) {
|
||
|
|
const error = new Error(message || '请求失败')
|
||
|
|
error.statusCode = statusCode
|
||
|
|
error.raw = raw
|
||
|
|
return error
|
||
|
|
}
|
||
|
|
|
||
|
|
function rawRequest(options) {
|
||
|
|
return new Promise((resolve, reject) => {
|
||
|
|
wx.request({
|
||
|
|
...options,
|
||
|
|
success: resolve,
|
||
|
|
fail: reject
|
||
|
|
})
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
function queueRequest(retry) {
|
||
|
|
return new Promise((resolve, reject) => {
|
||
|
|
requestQueue.push({
|
||
|
|
resolve,
|
||
|
|
reject,
|
||
|
|
retry
|
||
|
|
})
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
function flushQueue(error) {
|
||
|
|
const queue = requestQueue.slice()
|
||
|
|
requestQueue = []
|
||
|
|
|
||
|
|
queue.forEach(item => {
|
||
|
|
if (error) {
|
||
|
|
item.reject(error)
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
item.retry().then(item.resolve).catch(item.reject)
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
function redirectToAuth() {
|
||
|
|
if (redirectingToAuth) {
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
redirectingToAuth = true
|
||
|
|
const pages = getCurrentPages()
|
||
|
|
const current = pages[pages.length - 1]
|
||
|
|
const currentPath = current ? `/${current.route}` : '/pages/home/index'
|
||
|
|
const currentQuery = current && current.options ? current.options : {}
|
||
|
|
const queryString = Object.keys(currentQuery)
|
||
|
|
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(currentQuery[key])}`)
|
||
|
|
.join('&')
|
||
|
|
const redirect = queryString ? `${currentPath}?${queryString}` : currentPath
|
||
|
|
|
||
|
|
wx.showToast({
|
||
|
|
title: '登录已过期,请重新登录',
|
||
|
|
icon: 'none'
|
||
|
|
})
|
||
|
|
|
||
|
|
setTimeout(() => {
|
||
|
|
wx.reLaunch({
|
||
|
|
url: `/pages/auth/index?redirect=${encodeURIComponent(redirect)}`,
|
||
|
|
complete() {
|
||
|
|
redirectingToAuth = false
|
||
|
|
}
|
||
|
|
})
|
||
|
|
}, 300)
|
||
|
|
}
|
||
|
|
|
||
|
|
async function refreshToken() {
|
||
|
|
const refreshTokenValue = auth.getRefreshToken()
|
||
|
|
if (!refreshTokenValue) {
|
||
|
|
throw normalizeError('缺少刷新令牌', 401)
|
||
|
|
}
|
||
|
|
|
||
|
|
const response = await rawRequest({
|
||
|
|
url: `${API_BASE_URL}/user/refresh-token`,
|
||
|
|
method: 'POST',
|
||
|
|
timeout: REQUEST_TIMEOUT,
|
||
|
|
header: {
|
||
|
|
'Content-Type': 'application/json'
|
||
|
|
},
|
||
|
|
data: {
|
||
|
|
refreshToken: refreshTokenValue
|
||
|
|
}
|
||
|
|
})
|
||
|
|
|
||
|
|
if (response.statusCode === 200 && response.data && response.data.code === 200 && response.data.data) {
|
||
|
|
auth.setSession(response.data.data)
|
||
|
|
const app = getApp()
|
||
|
|
if (app && typeof app.bootstrapSession === 'function') {
|
||
|
|
app.bootstrapSession()
|
||
|
|
}
|
||
|
|
return response.data.data
|
||
|
|
}
|
||
|
|
|
||
|
|
throw normalizeError(
|
||
|
|
(response.data && response.data.message) || '刷新登录态失败',
|
||
|
|
response.statusCode,
|
||
|
|
response
|
||
|
|
)
|
||
|
|
}
|
||
|
|
|
||
|
|
async function handleUnauthorized(options) {
|
||
|
|
if (options._retry || isWhitelistedPath(options.url)) {
|
||
|
|
auth.clearSession()
|
||
|
|
const app = getApp()
|
||
|
|
if (app && typeof app.clearUserSession === 'function') {
|
||
|
|
app.clearUserSession()
|
||
|
|
}
|
||
|
|
redirectToAuth()
|
||
|
|
throw normalizeError('登录已过期,请重新登录', 401)
|
||
|
|
}
|
||
|
|
|
||
|
|
if (isRefreshing) {
|
||
|
|
return queueRequest(() => request({
|
||
|
|
...options,
|
||
|
|
_retry: true
|
||
|
|
}))
|
||
|
|
}
|
||
|
|
|
||
|
|
isRefreshing = true
|
||
|
|
try {
|
||
|
|
await refreshToken()
|
||
|
|
flushQueue(null)
|
||
|
|
return await request({
|
||
|
|
...options,
|
||
|
|
_retry: true
|
||
|
|
})
|
||
|
|
} catch (error) {
|
||
|
|
flushQueue(error)
|
||
|
|
auth.clearSession()
|
||
|
|
const app = getApp()
|
||
|
|
if (app && typeof app.clearUserSession === 'function') {
|
||
|
|
app.clearUserSession()
|
||
|
|
}
|
||
|
|
redirectToAuth()
|
||
|
|
throw error
|
||
|
|
} finally {
|
||
|
|
isRefreshing = false
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
function unwrapResponse(res, options) {
|
||
|
|
if (res.statusCode === 401) {
|
||
|
|
return handleUnauthorized(options)
|
||
|
|
}
|
||
|
|
|
||
|
|
if (res.statusCode >= 400) {
|
||
|
|
throw normalizeError(
|
||
|
|
(res.data && res.data.message) || '网络请求失败',
|
||
|
|
res.statusCode,
|
||
|
|
res
|
||
|
|
)
|
||
|
|
}
|
||
|
|
|
||
|
|
const payload = res.data
|
||
|
|
if (payload && typeof payload === 'object' && Object.prototype.hasOwnProperty.call(payload, 'code')) {
|
||
|
|
if (payload.code === 200) {
|
||
|
|
return payload.data
|
||
|
|
}
|
||
|
|
|
||
|
|
throw normalizeError(payload.message || '请求失败', payload.code, payload)
|
||
|
|
}
|
||
|
|
|
||
|
|
return payload
|
||
|
|
}
|
||
|
|
|
||
|
|
function request(options) {
|
||
|
|
const method = (options.method || 'GET').toUpperCase()
|
||
|
|
const header = {
|
||
|
|
'Content-Type': 'application/json',
|
||
|
|
...(options.header || {})
|
||
|
|
}
|
||
|
|
|
||
|
|
const accessToken = auth.getAccessToken()
|
||
|
|
if (accessToken) {
|
||
|
|
header.Authorization = `Bearer ${accessToken}`
|
||
|
|
}
|
||
|
|
|
||
|
|
const requestOptions = {
|
||
|
|
...options,
|
||
|
|
method,
|
||
|
|
header
|
||
|
|
}
|
||
|
|
|
||
|
|
return new Promise((resolve, reject) => {
|
||
|
|
wx.request({
|
||
|
|
url: buildRequestUrl(options.url, method === 'GET' ? options.params : undefined),
|
||
|
|
method,
|
||
|
|
timeout: options.timeout || REQUEST_TIMEOUT,
|
||
|
|
header,
|
||
|
|
data: method === 'GET' ? undefined : options.data,
|
||
|
|
success: async res => {
|
||
|
|
try {
|
||
|
|
const data = await unwrapResponse(res, requestOptions)
|
||
|
|
resolve(data)
|
||
|
|
} catch (error) {
|
||
|
|
reject(error)
|
||
|
|
}
|
||
|
|
},
|
||
|
|
fail: error => {
|
||
|
|
reject(normalizeError(error.errMsg || '网络异常,请稍后重试', 0, error))
|
||
|
|
}
|
||
|
|
})
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
module.exports = request
|