新增app连接缓存

This commit is contained in:
tianfeng 2025-08-21 16:48:48 +08:00
parent a556577599
commit fe54bd0b62
3 changed files with 324 additions and 53 deletions

View File

@ -0,0 +1,74 @@
// APP连接状态管理器
class AppConnectionManager {
constructor() {
this.connected = false
this.connecting = false
this.headerInfo = null
this.connectionPromise = null
this.lastConnectTime = null
this.connectionTimeout = 5 * 60 * 1000 // 5分钟超时重连
}
// 检查是否需要重新连接
needsReconnect() {
if (!this.connected) return true
if (!this.lastConnectTime) return true
const now = Date.now()
return (now - this.lastConnectTime) > this.connectionTimeout
}
// 获取连接状态
isConnected() {
return this.connected && !this.needsReconnect()
}
// 获取头部信息
getHeaderInfo() {
return this.headerInfo
}
// 设置连接状态
setConnected(headerInfo = null) {
this.connected = true
this.connecting = false
this.headerInfo = headerInfo
this.lastConnectTime = Date.now()
this.connectionPromise = null
console.debug('✅ APP连接状态已更新')
}
// 设置连接中状态
setConnecting(promise) {
this.connecting = true
this.connectionPromise = promise
}
// 重置连接状态
reset() {
this.connected = false
this.connecting = false
this.headerInfo = null
this.connectionPromise = null
this.lastConnectTime = null
console.debug('🔄 APP连接状态已重置')
}
// 获取当前连接Promise
getConnectionPromise() {
return this.connectionPromise
}
// 是否正在连接中
isConnecting() {
return this.connecting
}
}
// 创建全局实例
export const appConnectionManager = new AppConnectionManager()
// 导出便捷方法
export const isAppConnected = () => appConnectionManager.isConnected()
export const getAppHeaderInfo = () => appConnectionManager.getHeaderInfo()
export const resetAppConnection = () => appConnectionManager.reset()

View File

@ -0,0 +1,155 @@
import { appConnectionManager, isAppConnected, getAppHeaderInfo } from './appConnectionManager.js'
import { connectApplication, parseAccessOrigin, parseHeader, setHttpHeaders, isInApp } from './appBridge.js'
/**
* 优化的APP连接工具
* 避免重复连接提升性能
*/
export const useOptimizedAppConnection = () => {
// 优化的连接方法
const connectToAppOptimized = async (router, options = {}) => {
const {
fetchDataCallback = null,
onConnectionSuccess = null,
onConnectionFailed = null
} = options
console.group('🔗 Optimized APP Connection')
console.debug('🚀 Starting connection check...')
// 检查是否在APP环境中
if (!isInApp()) {
console.debug('🌐 Browser environment - skipping APP connection')
if (fetchDataCallback) {
await fetchDataCallback()
}
console.groupEnd()
return { success: true, fromCache: false }
}
// 检查是否已经连接且有效
if (isAppConnected()) {
console.debug('✅ Using existing valid connection')
const headerInfo = getAppHeaderInfo()
if (fetchDataCallback) {
await fetchDataCallback()
}
if (onConnectionSuccess) {
onConnectionSuccess(headerInfo)
}
console.groupEnd()
return { success: true, fromCache: true, headerInfo }
}
// 检查是否有进行中的连接
if (appConnectionManager.isConnecting()) {
console.debug('⏳ Waiting for existing connection...')
try {
await appConnectionManager.getConnectionPromise()
const headerInfo = getAppHeaderInfo()
if (fetchDataCallback) {
await fetchDataCallback()
}
if (onConnectionSuccess) {
onConnectionSuccess(headerInfo)
}
console.groupEnd()
return { success: true, fromCache: true, headerInfo }
} catch (error) {
console.error('❌ Existing connection failed:', error)
if (onConnectionFailed) {
onConnectionFailed(error)
}
console.groupEnd()
return { success: false, error }
}
}
// 建立新连接
console.debug('📱 Establishing new APP connection...')
const connectionPromise = new Promise((resolve, reject) => {
connectApplication(async (access) => {
try {
const result = parseAccessOrigin(access)
if (result.success) {
const headerInfo = parseHeader(result.data)
await setHttpHeaders(headerInfo)
// 更新连接状态
appConnectionManager.setConnected(headerInfo)
console.debug('🎉 New connection established')
if (fetchDataCallback) {
await fetchDataCallback()
}
if (onConnectionSuccess) {
onConnectionSuccess(headerInfo)
}
resolve({ success: true, fromCache: false, headerInfo })
} else {
console.error('❌ Failed to parse access:', result.error)
appConnectionManager.reset()
if (router) {
router.push({ path: '/not_app', query: { message: result.error }})
}
if (onConnectionFailed) {
onConnectionFailed(new Error(result.error))
}
reject(new Error(result.error))
}
} catch (error) {
console.error('❌ Connection process failed:', error)
appConnectionManager.reset()
if (onConnectionFailed) {
onConnectionFailed(error)
}
reject(error)
}
})
})
appConnectionManager.setConnecting(connectionPromise)
try {
const result = await connectionPromise
console.groupEnd()
return result
} catch (error) {
console.groupEnd()
return { success: false, error }
}
}
// 重置连接
const resetConnection = () => {
appConnectionManager.reset()
}
// 检查连接状态
const checkConnectionStatus = () => {
return {
isConnected: isAppConnected(),
isConnecting: appConnectionManager.isConnecting(),
headerInfo: getAppHeaderInfo()
}
}
return {
connectToAppOptimized,
resetConnection,
checkConnectionStatus,
isAppConnected,
getAppHeaderInfo
}
}

View File

@ -130,6 +130,7 @@ import { useRouter } from 'vue-router'
import MobileHeader from '../components/MobileHeader.vue'
import { getBankBalance, getUserIdentity, getTeamEntry, getTeamMemberWorkStatistics } from '../api/wallet.js'
import { connectApplication, parseAccessOrigin, parseHeader, setHttpHeaders, isInApp } from '../utils/appBridge.js'
import { appConnectionManager, isAppConnected, getAppHeaderInfo } from '../utils/appConnectionManager.js'
import {getUserId, setUserInfo} from '../utils/userStore.js'
import {showError} from "@/utils/toast.js";
@ -143,19 +144,15 @@ const headerInfo = ref({})
const userProfile = ref(null)
const identityChecked = ref(false)
// APP
// APP
const connectToApp = async () => {
console.group('🔗 APP Connection Process')
console.debug('🚀 Starting APP connection...')
console.group('🔗 APP Connection Process (Optimized)')
console.debug('🚀 Starting optimized APP connection...')
// APP
if (!isInApp()) {
console.warn('⚠️ Not running in APP environment')
console.debug('🌐 Browser environment detected')
console.debug('📱 APP Bridge objects:')
console.debug(' - window.app:', !!window.app)
console.debug(' - window.webkit:', !!window.webkit)
// APP
appConnected.value = true
console.debug('✅ Skipping APP connection, proceeding with team entry')
await fetchTeamEntry()
@ -163,49 +160,98 @@ const connectToApp = async () => {
return
}
console.debug('📱 APP environment detected')
console.debug('🔍 Checking APP bridge availability:')
console.debug(' - window.app:', !!window.app)
console.debug(' - window.webkit:', !!window.webkit)
//
if (isAppConnected()) {
console.debug('✅ APP already connected and valid')
appConnected.value = true
connectApplication(async (access) => {
const result = parseAccessOrigin(access)
if (result.success) {
//
headerInfo.value = parseHeader(result.data)
// HTTP
console.debug('🔧 Setting HTTP headers...')
await setHttpHeaders(headerInfo.value)
//
appConnected.value = true
console.debug('🎉 APP connection established successfully')
//
console.debug('📊 Fetching team entry and bank balance...')
const teamEntryResult = await fetchTeamEntry()
console.debug('✅ Team entry fetched')
if (teamEntryResult != null) {
await fetchBankBalance()
console.debug('✅ Bank balance fetch initiated')
await fetchWorkStatistics()
console.debug('✅ Work statistics fetch initiated')
}
} else {
console.error('❌ Failed to parse access origin:', result.error)
console.debug('🔄 Redirecting to error page...')
//
router.push({ path: '/not_app', query: { message: result.error }})
// 使
const cachedHeaderInfo = getAppHeaderInfo()
if (cachedHeaderInfo) {
headerInfo.value = cachedHeaderInfo
console.debug('🔧 Using cached HTTP headers')
}
console.debug('📊 Fetching data with existing connection...')
const teamEntryResult = await fetchTeamEntry()
if (teamEntryResult != null) {
await fetchBankBalance()
await fetchWorkStatistics()
}
console.groupEnd()
return
}
//
if (appConnectionManager.isConnecting()) {
console.debug('⏳ Connection already in progress, waiting...')
try {
await appConnectionManager.getConnectionPromise()
appConnected.value = true
console.debug('✅ Connected via existing process')
console.groupEnd()
return
} catch (error) {
console.error('❌ Failed to wait for existing connection:', error)
}
}
console.debug('📱 APP environment detected, establishing new connection')
// Promise
const connectionPromise = new Promise((resolve, reject) => {
connectApplication(async (access) => {
try {
const result = parseAccessOrigin(access)
if (result.success) {
//
headerInfo.value = parseHeader(result.data)
// HTTP
console.debug('🔧 Setting HTTP headers...')
await setHttpHeaders(headerInfo.value)
//
appConnected.value = true
appConnectionManager.setConnected(headerInfo.value)
console.debug('🎉 APP connection established successfully')
//
console.debug('📊 Fetching team entry and bank balance...')
const teamEntryResult = await fetchTeamEntry()
if (teamEntryResult != null) {
await fetchBankBalance()
await fetchWorkStatistics()
}
resolve()
} else {
console.error('❌ Failed to parse access origin:', result.error)
appConnectionManager.reset()
router.push({ path: '/not_app', query: { message: result.error }})
reject(new Error(result.error))
}
} catch (error) {
console.error('❌ Connection process failed:', error)
appConnectionManager.reset()
reject(error)
}
})
})
console.debug('⏳ Waiting for APP response...')
//
appConnectionManager.setConnecting(connectionPromise)
try {
await connectionPromise
console.debug('✅ Connection completed successfully')
} catch (error) {
console.error('❌ Connection failed:', error)
}
console.groupEnd()
}
//
@ -405,16 +451,12 @@ const transfer = () => {
router.push('/transfer')
}
// APP
//
onMounted(async () => {
// APP
await connectToApp()
console.debug('📄 HostCenterView mounted')
// APP
if (!isInApp()) {
await fetchBankBalance()
await fetchWorkStatistics()
}
// APP
await connectToApp()
})
</script>