Files
past-go/weapp/utils/user-location.js
2026-10-26 17:32:47 +08:00

36 lines
1.5 KiB
JavaScript

const { api } = require('./request');
let pending = null;
let cached = null;
let cachedAt = 0;
let user = null;
function address(value) {
const text = String(value || '').trim();
return /^-?\d+(\.\d+)?,\s*-?\d+(\.\d+)?$/.test(text) ? '' : text;
}
async function currentUserLocation() {
const uid = wx.getStorageSync('userId');
if (user !== uid) { user = uid; pending = null; cached = null; cachedAt = 0; }
if (cached && Date.now() - cachedAt < 45000) return { ...cached };
if (pending) return pending;
const task = (async () => {
let coords = { lat: 0, lng: 0 };
try {
if (wx.getFuzzyLocation) coords = await new Promise(resolve => wx.getFuzzyLocation({ type: 'gcj02', success: res => resolve({lat: res.latitude, lng: res.longitude}), fail: () => resolve(coords) }));
const result = await api.updateIpLocation(coords);
if (address(result && result.location)) return { ...coords, location: address(result.location) };
} catch (error) {}
try {
const info = await api.coupleInfo();
const me = [info.partner1, info.partner2].find(partner => partner && String(partner.id) === String(uid));
return { ...coords, location: address(me && me.location) };
} catch (error) { return { ...coords, location: '' }; }
})();
pending = task;
try {
const result = await task;
if (user === uid && pending === task && result.location) { cached = result; cachedAt = Date.now(); }
return result;
} finally { if (pending === task) pending = null; }
}
module.exports = { currentUserLocation };