功能:新增微信小程序界面
This commit is contained in:
@@ -0,0 +1,77 @@
|
||||
const { STORAGE_KEYS, getStorage, removeStorage, setStorage } = require('./storage')
|
||||
|
||||
function getAccessToken() {
|
||||
return getStorage(STORAGE_KEYS.ACCESS_TOKEN, '')
|
||||
}
|
||||
|
||||
function getRefreshToken() {
|
||||
return getStorage(STORAGE_KEYS.REFRESH_TOKEN, '')
|
||||
}
|
||||
|
||||
function getStoredUserInfo() {
|
||||
return getStorage(STORAGE_KEYS.USER_INFO, null)
|
||||
}
|
||||
|
||||
function getNeedSetPassword() {
|
||||
return Boolean(getStorage(STORAGE_KEYS.NEED_SET_PASSWORD, false))
|
||||
}
|
||||
|
||||
function isLoggedIn() {
|
||||
return Boolean(getAccessToken())
|
||||
}
|
||||
|
||||
function setSession(payload) {
|
||||
if (!payload || !payload.accessToken || !payload.refreshToken) {
|
||||
return
|
||||
}
|
||||
|
||||
setStorage(STORAGE_KEYS.ACCESS_TOKEN, payload.accessToken)
|
||||
setStorage(STORAGE_KEYS.REFRESH_TOKEN, payload.refreshToken)
|
||||
|
||||
if (payload.userInfo) {
|
||||
setStorage(STORAGE_KEYS.USER_INFO, payload.userInfo)
|
||||
}
|
||||
|
||||
if (payload.needSetPassword) {
|
||||
setStorage(STORAGE_KEYS.NEED_SET_PASSWORD, true)
|
||||
} else {
|
||||
removeStorage(STORAGE_KEYS.NEED_SET_PASSWORD)
|
||||
}
|
||||
}
|
||||
|
||||
function updateStoredUserInfo(userInfo) {
|
||||
if (!userInfo) {
|
||||
removeStorage(STORAGE_KEYS.USER_INFO)
|
||||
return
|
||||
}
|
||||
|
||||
setStorage(STORAGE_KEYS.USER_INFO, userInfo)
|
||||
}
|
||||
|
||||
function setNeedSetPassword(value) {
|
||||
if (value) {
|
||||
setStorage(STORAGE_KEYS.NEED_SET_PASSWORD, true)
|
||||
return
|
||||
}
|
||||
|
||||
removeStorage(STORAGE_KEYS.NEED_SET_PASSWORD)
|
||||
}
|
||||
|
||||
function clearSession() {
|
||||
removeStorage(STORAGE_KEYS.ACCESS_TOKEN)
|
||||
removeStorage(STORAGE_KEYS.REFRESH_TOKEN)
|
||||
removeStorage(STORAGE_KEYS.USER_INFO)
|
||||
removeStorage(STORAGE_KEYS.NEED_SET_PASSWORD)
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getAccessToken,
|
||||
getRefreshToken,
|
||||
getStoredUserInfo,
|
||||
getNeedSetPassword,
|
||||
isLoggedIn,
|
||||
setSession,
|
||||
updateStoredUserInfo,
|
||||
setNeedSetPassword,
|
||||
clearSession
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
function getEnvVersion() {
|
||||
if (typeof wx === 'undefined') {
|
||||
return 'develop'
|
||||
}
|
||||
|
||||
try {
|
||||
if (typeof wx.getAccountInfoSync === 'function') {
|
||||
const accountInfo = wx.getAccountInfoSync()
|
||||
const miniProgram = accountInfo && accountInfo.miniProgram
|
||||
if (miniProgram && miniProgram.envVersion) {
|
||||
return miniProgram.envVersion
|
||||
}
|
||||
}
|
||||
} catch (error) {}
|
||||
|
||||
try {
|
||||
if (typeof __wxConfig !== 'undefined' && __wxConfig && __wxConfig.envVersion) {
|
||||
return __wxConfig.envVersion
|
||||
}
|
||||
} catch (error) {}
|
||||
|
||||
return 'develop'
|
||||
}
|
||||
|
||||
function getRuntimePlatform() {
|
||||
if (typeof wx === 'undefined') {
|
||||
return 'devtools'
|
||||
}
|
||||
|
||||
try {
|
||||
if (typeof wx.getDeviceInfo === 'function') {
|
||||
const deviceInfo = wx.getDeviceInfo()
|
||||
if (deviceInfo && deviceInfo.platform) {
|
||||
return deviceInfo.platform
|
||||
}
|
||||
}
|
||||
} catch (error) {}
|
||||
|
||||
try {
|
||||
if (typeof wx.getSystemInfoSync === 'function') {
|
||||
const systemInfo = wx.getSystemInfoSync()
|
||||
if (systemInfo && systemInfo.platform) {
|
||||
return systemInfo.platform
|
||||
}
|
||||
}
|
||||
} catch (error) {}
|
||||
|
||||
return 'unknown'
|
||||
}
|
||||
|
||||
const ENV_VERSION = getEnvVersion()
|
||||
const RUNTIME_PLATFORM = getRuntimePlatform()
|
||||
const IS_DEVTOOLS = RUNTIME_PLATFORM === 'devtools'
|
||||
|
||||
const LOCAL_API_DOMAIN = 'http://127.0.0.1:80'
|
||||
const REMOTE_API_DOMAIN = 'https://yunail.art'
|
||||
const USE_LOCAL_API = ENV_VERSION === 'develop' && IS_DEVTOOLS
|
||||
const API_DOMAIN = USE_LOCAL_API ? LOCAL_API_DOMAIN : REMOTE_API_DOMAIN
|
||||
|
||||
module.exports = {
|
||||
ENV_VERSION,
|
||||
RUNTIME_PLATFORM,
|
||||
IS_DEVTOOLS,
|
||||
USE_LOCAL_API,
|
||||
API_DOMAIN,
|
||||
API_BASE_URL: `${API_DOMAIN}/api`,
|
||||
IS_DEV_ENV: ENV_VERSION === 'develop',
|
||||
REQUEST_TIMEOUT: 10000,
|
||||
DEFAULT_AVATAR: 'https://api.dicebear.com/7.x/avataaars/svg?seed=default',
|
||||
DEFAULT_PRODUCT_IMAGE: 'https://via.placeholder.com/200x200?text=Product',
|
||||
DEFAULT_SHOP_IMAGE: 'https://via.placeholder.com/200x200?text=Shop',
|
||||
NO_COUPON_KEY: 'NONE',
|
||||
TAB_PAGES: [
|
||||
'/pages/home/index',
|
||||
'/pages/products/index',
|
||||
'/pages/cart/index',
|
||||
'/pages/profile/index'
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
const fileApi = require('../api/file')
|
||||
const { DEFAULT_PRODUCT_IMAGE } = require('./config')
|
||||
const { splitCsv } = require('./format')
|
||||
|
||||
const urlCache = {}
|
||||
|
||||
async function getSignedUrl(fileId) {
|
||||
const key = String(fileId || '')
|
||||
if (!key) {
|
||||
return ''
|
||||
}
|
||||
|
||||
if (!urlCache[key]) {
|
||||
urlCache[key] = await fileApi.getSignedUrl(key)
|
||||
}
|
||||
|
||||
return urlCache[key] || ''
|
||||
}
|
||||
|
||||
function extractLegacyFileId(value) {
|
||||
const match = String(value || '')
|
||||
.replace(/<[^>]*>/g, '')
|
||||
.match(/\/api\/file\/get\/(\d+)/)
|
||||
|
||||
return match && match[1] ? match[1] : ''
|
||||
}
|
||||
|
||||
async function resolveImageList(fileIds, fallbackImage) {
|
||||
const ids = Array.isArray(fileIds) ? fileIds : splitCsv(fileIds)
|
||||
if (!ids.length) {
|
||||
return [fallbackImage || DEFAULT_PRODUCT_IMAGE]
|
||||
}
|
||||
|
||||
const urls = []
|
||||
for (let index = 0; index < ids.length; index += 1) {
|
||||
const fileId = ids[index]
|
||||
try {
|
||||
const url = await getSignedUrl(fileId)
|
||||
if (url) {
|
||||
urls.push(url)
|
||||
}
|
||||
} catch (error) {}
|
||||
}
|
||||
|
||||
return urls.length ? urls : [fallbackImage || DEFAULT_PRODUCT_IMAGE]
|
||||
}
|
||||
|
||||
async function resolveLegacyImage(value, fallbackImage) {
|
||||
const fileId = extractLegacyFileId(value)
|
||||
if (!fileId) {
|
||||
return fallbackImage || DEFAULT_PRODUCT_IMAGE
|
||||
}
|
||||
|
||||
try {
|
||||
const url = await getSignedUrl(fileId)
|
||||
return url || fallbackImage || DEFAULT_PRODUCT_IMAGE
|
||||
} catch (error) {
|
||||
return fallbackImage || DEFAULT_PRODUCT_IMAGE
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getSignedUrl,
|
||||
extractLegacyFileId,
|
||||
resolveImageList,
|
||||
resolveLegacyImage
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
function formatPrice(value) {
|
||||
return Number(value || 0).toFixed(2)
|
||||
}
|
||||
|
||||
function getProductTitle(product) {
|
||||
return (product && (product.title || product.name)) || '未命名作品'
|
||||
}
|
||||
|
||||
function splitCsv(value) {
|
||||
return String(value || '')
|
||||
.split(',')
|
||||
.map(item => item.trim())
|
||||
.filter(Boolean)
|
||||
}
|
||||
|
||||
function sameId(left, right) {
|
||||
return String(left || '') === String(right || '')
|
||||
}
|
||||
|
||||
function formatDateTime(value) {
|
||||
if (!value) {
|
||||
return ''
|
||||
}
|
||||
return String(value).replace('T', ' ').slice(0, 16)
|
||||
}
|
||||
|
||||
function parseAppointmentParts(value) {
|
||||
const text = formatDateTime(value)
|
||||
if (!text) {
|
||||
return {
|
||||
date: '',
|
||||
clock: ''
|
||||
}
|
||||
}
|
||||
|
||||
const parts = text.split(' ')
|
||||
return {
|
||||
date: parts[0] || '',
|
||||
clock: parts[1] || ''
|
||||
}
|
||||
}
|
||||
|
||||
function buildAppointmentValue(date, clock) {
|
||||
if (!date || !clock) {
|
||||
return ''
|
||||
}
|
||||
return `${date} ${clock}:00`
|
||||
}
|
||||
|
||||
function isPastAppointment(value) {
|
||||
if (!value) {
|
||||
return false
|
||||
}
|
||||
return new Date(String(value).replace(' ', 'T')).getTime() < Date.now() + 5 * 60 * 1000
|
||||
}
|
||||
|
||||
function getMinDateText() {
|
||||
const now = new Date()
|
||||
const year = now.getFullYear()
|
||||
const month = String(now.getMonth() + 1).padStart(2, '0')
|
||||
const date = String(now.getDate()).padStart(2, '0')
|
||||
return `${year}-${month}-${date}`
|
||||
}
|
||||
|
||||
function getOrderStatusText(order) {
|
||||
if (order && order.statusText) {
|
||||
return order.statusText
|
||||
}
|
||||
|
||||
const status = Number(order && order.status)
|
||||
if (status === 1) {
|
||||
return '待服务'
|
||||
}
|
||||
if (status === 2) {
|
||||
return '已完成'
|
||||
}
|
||||
return '已取消'
|
||||
}
|
||||
|
||||
function getOrderStatusClass(order) {
|
||||
const status = Number(order && order.status)
|
||||
if (status === 1) {
|
||||
return 'pending'
|
||||
}
|
||||
if (status === 2) {
|
||||
return 'completed'
|
||||
}
|
||||
return 'cancelled'
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
formatPrice,
|
||||
getProductTitle,
|
||||
splitCsv,
|
||||
sameId,
|
||||
formatDateTime,
|
||||
parseAppointmentParts,
|
||||
buildAppointmentValue,
|
||||
isPastAppointment,
|
||||
getMinDateText,
|
||||
getOrderStatusText,
|
||||
getOrderStatusClass
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
let activeLoadingCount = 0
|
||||
|
||||
function showLoading(options) {
|
||||
const config = options || {}
|
||||
activeLoadingCount += 1
|
||||
|
||||
if (activeLoadingCount > 1) {
|
||||
return
|
||||
}
|
||||
|
||||
wx.showLoading({
|
||||
title: config.title || '\u52a0\u8f7d\u4e2d',
|
||||
mask: config.mask !== false
|
||||
})
|
||||
}
|
||||
|
||||
function hideLoading() {
|
||||
activeLoadingCount = Math.max(0, activeLoadingCount - 1)
|
||||
|
||||
if (activeLoadingCount > 0) {
|
||||
return
|
||||
}
|
||||
|
||||
wx.hideLoading({
|
||||
fail() {}
|
||||
})
|
||||
}
|
||||
|
||||
function resetLoading() {
|
||||
activeLoadingCount = 0
|
||||
wx.hideLoading({
|
||||
fail() {}
|
||||
})
|
||||
}
|
||||
|
||||
function runWithLoading(task, options) {
|
||||
showLoading(options)
|
||||
|
||||
return Promise.resolve()
|
||||
.then(() => task())
|
||||
.finally(() => {
|
||||
hideLoading()
|
||||
})
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
showLoading,
|
||||
hideLoading,
|
||||
resetLoading,
|
||||
runWithLoading
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
const auth = require('./auth')
|
||||
const { TAB_PAGES } = require('./config')
|
||||
|
||||
function buildUrl(path, params) {
|
||||
const query = Object.keys(params || {})
|
||||
.filter(key => params[key] !== undefined && params[key] !== null && params[key] !== '')
|
||||
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
|
||||
.join('&')
|
||||
|
||||
return query ? `${path}?${query}` : path
|
||||
}
|
||||
|
||||
function getCurrentPageUrl() {
|
||||
const pages = getCurrentPages()
|
||||
const current = pages[pages.length - 1]
|
||||
if (!current) {
|
||||
return '/pages/home/index'
|
||||
}
|
||||
|
||||
return buildUrl(`/${current.route}`, current.options || {})
|
||||
}
|
||||
|
||||
function isTabPage(path) {
|
||||
const purePath = String(path || '').split('?')[0]
|
||||
return TAB_PAGES.includes(purePath)
|
||||
}
|
||||
|
||||
function navigate(path, params) {
|
||||
return new Promise((resolve, reject) => {
|
||||
wx.navigateTo({
|
||||
url: buildUrl(path, params),
|
||||
success: resolve,
|
||||
fail: reject
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function switchTab(path) {
|
||||
return new Promise((resolve, reject) => {
|
||||
wx.switchTab({
|
||||
url: path,
|
||||
success: resolve,
|
||||
fail: reject
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function goBack(fallbackPath) {
|
||||
const pages = getCurrentPages()
|
||||
if (pages.length > 1) {
|
||||
wx.navigateBack()
|
||||
return
|
||||
}
|
||||
|
||||
if (isTabPage(fallbackPath || '/pages/home/index')) {
|
||||
wx.switchTab({
|
||||
url: fallbackPath || '/pages/home/index'
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
wx.redirectTo({
|
||||
url: fallbackPath || '/pages/home/index'
|
||||
})
|
||||
}
|
||||
|
||||
function parseQuery(url) {
|
||||
const queryString = String(url || '').split('?')[1] || ''
|
||||
if (!queryString) {
|
||||
return {}
|
||||
}
|
||||
|
||||
return queryString.split('&').reduce((result, item) => {
|
||||
const parts = item.split('=')
|
||||
const key = decodeURIComponent(parts[0] || '')
|
||||
const value = decodeURIComponent(parts[1] || '')
|
||||
if (key) {
|
||||
result[key] = value
|
||||
}
|
||||
return result
|
||||
}, {})
|
||||
}
|
||||
|
||||
function decodeRedirectValue(value) {
|
||||
let current = String(value || '')
|
||||
|
||||
for (let index = 0; index < 3; index += 1) {
|
||||
try {
|
||||
const decoded = decodeURIComponent(current)
|
||||
if (decoded === current) {
|
||||
return decoded
|
||||
}
|
||||
current = decoded
|
||||
} catch (error) {
|
||||
return current
|
||||
}
|
||||
}
|
||||
|
||||
return current
|
||||
}
|
||||
|
||||
function redirectAfterLogin(redirect) {
|
||||
const target = redirect ? decodeRedirectValue(redirect) : ''
|
||||
if (!target) {
|
||||
return switchTab('/pages/home/index')
|
||||
}
|
||||
|
||||
const purePath = target.split('?')[0]
|
||||
if (purePath === '/pages/products/index') {
|
||||
const app = getApp()
|
||||
app.globalData.pendingProductFilter = parseQuery(target)
|
||||
return switchTab('/pages/products/index')
|
||||
}
|
||||
|
||||
if (isTabPage(target)) {
|
||||
return switchTab(purePath)
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
wx.redirectTo({
|
||||
url: target,
|
||||
success: resolve,
|
||||
fail: reject
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function openAuth(redirect) {
|
||||
return navigate('/pages/auth/index', {
|
||||
redirect: redirect || getCurrentPageUrl()
|
||||
})
|
||||
}
|
||||
|
||||
function ensureLogin(actionText) {
|
||||
if (auth.isLoggedIn()) {
|
||||
return true
|
||||
}
|
||||
|
||||
wx.showToast({
|
||||
title: `${actionText || '继续操作'}前请先登录`,
|
||||
icon: 'none'
|
||||
})
|
||||
|
||||
setTimeout(() => {
|
||||
openAuth()
|
||||
}, 120)
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
function openProducts(filter) {
|
||||
const app = getApp()
|
||||
app.globalData.pendingProductFilter = filter || {}
|
||||
return switchTab('/pages/products/index')
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
buildUrl,
|
||||
getCurrentPageUrl,
|
||||
isTabPage,
|
||||
navigate,
|
||||
switchTab,
|
||||
goBack,
|
||||
redirectAfterLogin,
|
||||
openAuth,
|
||||
ensureLogin,
|
||||
openProducts
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
const { formatPrice, getProductTitle } = require('./format')
|
||||
const { resolveImageList } = require('./file')
|
||||
const { DEFAULT_PRODUCT_IMAGE } = require('./config')
|
||||
|
||||
function getProductTags(product) {
|
||||
if (Array.isArray(product && product.tagInfos)) {
|
||||
return product.tagInfos
|
||||
.map(tag => tag && tag.tagName)
|
||||
.filter(Boolean)
|
||||
.slice(0, 3)
|
||||
}
|
||||
|
||||
return []
|
||||
}
|
||||
|
||||
async function buildProductCard(product) {
|
||||
const images = await resolveImageList(product && product.imageFileIds, DEFAULT_PRODUCT_IMAGE)
|
||||
return {
|
||||
...product,
|
||||
displayTitle: getProductTitle(product),
|
||||
priceText: `¥${formatPrice(product && product.price)}`,
|
||||
metaText: (product && (product.approximateDuration || product.shopName)) || '支持预约',
|
||||
coverUrl: images[0],
|
||||
imageUrls: images,
|
||||
tagsPreview: getProductTags(product),
|
||||
statsText: `${Number(product && product.likeCount || 0)}赞 · ${Number(product && product.collectCount || 0)}藏`
|
||||
}
|
||||
}
|
||||
|
||||
async function buildProductCards(products) {
|
||||
const list = Array.isArray(products) ? products : []
|
||||
return Promise.all(list.map(item => buildProductCard(item)))
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
buildProductCard,
|
||||
buildProductCards
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
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
|
||||
@@ -0,0 +1,30 @@
|
||||
const STORAGE_KEYS = {
|
||||
ACCESS_TOKEN: 'accessToken',
|
||||
REFRESH_TOKEN: 'refreshToken',
|
||||
USER_INFO: 'userInfo',
|
||||
NEED_SET_PASSWORD: 'needSetPassword'
|
||||
}
|
||||
|
||||
function getStorage(key, defaultValue) {
|
||||
try {
|
||||
const value = wx.getStorageSync(key)
|
||||
return value === '' || value === undefined ? defaultValue : value
|
||||
} catch (error) {
|
||||
return defaultValue
|
||||
}
|
||||
}
|
||||
|
||||
function setStorage(key, value) {
|
||||
wx.setStorageSync(key, value)
|
||||
}
|
||||
|
||||
function removeStorage(key) {
|
||||
wx.removeStorageSync(key)
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
STORAGE_KEYS,
|
||||
getStorage,
|
||||
setStorage,
|
||||
removeStorage
|
||||
}
|
||||
Reference in New Issue
Block a user