chore: 补全工程配置,部署云函数,建立数据库索引

- 新增 .gitignore(排除 node_modules、私有配置、编译产物)
- 新增 cloudbaserc.json,绑定云环境 cloud1-d4g697lte499543d8
- project.config.json:补 miniprogramRoot、开启 useCompilerPlugins typescript,修复预览报 app.json 找不到的问题
- tsconfig.json:移除无效 typeRoots,解除 TypeScript 编译阻断
- miniprogram/app.json:移除 glass-easel(需基础库 3.x,兼容性差)
- miniprogram/utils/constants.ts:填入真实云环境 ID
- cloudfunctions/updateLocation:位置字段改用 GeoPoint 以支持地理索引
- cloudfunctions/getNearbyPets:改用 geoNear 聚合管道,支持真实距离排序

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
2026-06-06 00:37:33 +08:00
parent c04c890186
commit 24891d9004
8 changed files with 161 additions and 74 deletions

View File

@@ -3,74 +3,64 @@ cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()
const _ = db.command
// 粗略经纬度范围换算1度≈111km
function latDelta(km) { return km / 111 }
function lngDelta(km, lat) { return km / (111 * Math.cos(lat * Math.PI / 180)) }
function calcDistance(lat1, lng1, lat2, lng2) {
const R = 6371
const dLat = (lat2 - lat1) * Math.PI / 180
const dLng = (lng2 - lng1) * Math.PI / 180
const a = Math.sin(dLat / 2) ** 2 +
Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * Math.sin(dLng / 2) ** 2
return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)) * 1000 // meters
}
exports.main = async (event, context) => {
const { OPENID } = cloud.getWXContext()
const { latitude, longitude, radiusKm = 5 } = event
const {
latitude,
longitude,
maxDistance = 5000, // 默认 5km单位
page = 0,
pageSize = 20,
} = event
if (!latitude || !longitude) {
return { code: -1, message: '缺少位置信息' }
}
// 在线判断60秒内更新过位置的用户为在线
const onlineThreshold = new Date(Date.now() - 60 * 1000).toISOString()
if (!latitude || !longitude) return { code: -1, message: '缺少位置' }
try {
const dLat = latDelta(radiusKm)
const dLng = lngDelta(radiusKm, latitude)
const usersRes = await db.collection('users')
.where(
_.and([
{ openid: _.neq(OPENID) }, // 排除自己
{ 'lastLocation.latitude': _.gt(latitude - dLat).and(_.lt(latitude + dLat)) },
{ 'lastLocation.longitude': _.gt(longitude - dLng).and(_.lt(longitude + dLng)) },
{ pets: _.exists(true) },
])
)
.field({
openid: true, nickName: true, avatarUrl: true,
lastLocation: true, lastSeen: true, isOnline: true,
pets: true, location: true, bio: true,
// ✅ geoNear 聚合管道:依赖 users.lastLocation 字段上的 2dsphere 地理位置索引
const { list } = await db.collection('users')
.aggregate()
.geoNear({
near: db.Geo.Point(longitude, latitude), // 注意CloudBase GeoPoint 是 (lng, lat) 顺序
spherical: true,
distanceField: 'dist', // 在每条记录上附加实际距离(米)
maxDistance,
query: {
openid: _.neq(OPENID), // 排除自己
'pets.0': _.exists(true), // 至少有一只宠物
},
})
.limit(30)
.get()
const nearby = usersRes.data
.map(user => {
const userLat = user.lastLocation?.latitude
const userLng = user.lastLocation?.longitude
if (!userLat || !userLng) return null
const distance = calcDistance(latitude, longitude, userLat, userLng)
if (distance > radiusKm * 1000) return null
return {
userId: user.openid,
user,
pet: user.pets?.[0] || null,
distance,
isOnline: user.isOnline && user.lastSeen > onlineThreshold,
location: { latitude: userLat, longitude: userLng },
}
.skip(page * pageSize)
.limit(pageSize)
.project({
openid: false,
})
.filter(Boolean)
.sort((a, b) => a.distance - b.distance)
.end()
return { code: 0, data: nearby }
// 在线状态5 分钟内活跃
const fiveMin = 5 * 60 * 1000
const now = Date.now()
const result = list.map(u => ({
userId: u._id,
user: u,
pet: u.pets?.[0] || null,
distance: Math.round(u.dist),
distanceText: formatDist(u.dist),
isOnline: u.lastSeen && (now - new Date(u.lastSeen).getTime()) < fiveMin,
location: {
latitude: u.lastLocation?.coordinates?.[1],
longitude: u.lastLocation?.coordinates?.[0],
},
}))
return { code: 0, data: result }
} catch (e) {
return { code: -1, message: e.message }
}
}
function formatDist(meters) {
if (!meters && meters !== 0) return '未知'
if (meters < 1000) return Math.round(meters) + 'm'
return (meters / 1000).toFixed(1) + 'km'
}