import { UserProfile, GeoPoint } from './types/index' import { getCachedUser, login } from './utils/auth' import { CLOUD_ENV, HEARTBEAT_INTERVAL_MS } from './utils/constants' import { api } from './utils/api' App<{ userInfo: UserProfile | null isLoggedIn: boolean currentLocation: GeoPoint | null _locationTimer: number | null }>({ globalData: { userInfo: null, isLoggedIn: false, currentLocation: null, _locationTimer: null, }, onLaunch() { wx.cloud.init({ env: CLOUD_ENV, traceUser: true, }) const cached = getCachedUser() if (cached) { this.globalData.userInfo = cached this.globalData.isLoggedIn = true } this._initLocation() }, onShow() { this._startLocationHeartbeat() }, onHide() { this._stopLocationHeartbeat() }, async _initLogin() { try { const userInfo = await login() this.globalData.userInfo = userInfo this.globalData.isLoggedIn = true } catch (e) { console.error('Login failed', e) } }, _initLocation() { wx.getLocation({ type: 'gcj02', success: res => { this.globalData.currentLocation = { latitude: res.latitude, longitude: res.longitude, } if (this.globalData.isLoggedIn) { api.updateLocation(res.latitude, res.longitude).catch(() => {}) } }, fail: () => {}, }) }, _startLocationHeartbeat() { if (this.globalData._locationTimer) return this.globalData._locationTimer = setInterval(() => { if (!this.globalData.isLoggedIn) return wx.getLocation({ type: 'gcj02', success: res => { this.globalData.currentLocation = { latitude: res.latitude, longitude: res.longitude, } api.updateLocation(res.latitude, res.longitude).catch(() => {}) }, fail: () => {}, }) }, HEARTBEAT_INTERVAL_MS) }, _stopLocationHeartbeat() { if (this.globalData._locationTimer) { clearInterval(this.globalData._locationTimer) this.globalData._locationTimer = null } }, })