修复动态发布与互动问题
This commit is contained in:
@@ -5,17 +5,36 @@ const db = cloud.database()
|
||||
|
||||
exports.main = async event => {
|
||||
const { OPENID } = cloud.getWXContext()
|
||||
|
||||
// Reading a non-existent collection throws in WeChat 云开发, and this function
|
||||
// starts with a read — so the collection would never get created by the later
|
||||
// add(). Create it up-front (no-op if it already exists) to break that deadlock.
|
||||
try {
|
||||
await db.createCollection('locations')
|
||||
} catch (e) {
|
||||
// -501001 / "already exists" is expected on every call after the first.
|
||||
}
|
||||
|
||||
const now = Date.now()
|
||||
const loc = event.location || null
|
||||
const visible = Boolean(event.visible)
|
||||
const hasCoord = loc && typeof loc.latitude === 'number' && typeof loc.longitude === 'number'
|
||||
|
||||
const data = {
|
||||
openid: OPENID,
|
||||
location: event.location || null,
|
||||
visible: Boolean(event.visible),
|
||||
location: hasCoord ? { latitude: loc.latitude, longitude: loc.longitude } : null,
|
||||
// `nearbyPets` currently filters by distance in memory off `location`, so the
|
||||
// `visible` flag below is what gates discovery. `geo` is kept (Point form) only
|
||||
// to enable a future geoNear migration if the user base outgrows the in-memory
|
||||
// scan — it needs a manually-created geo index to be queried.
|
||||
geo: hasCoord && visible ? db.Geo.Point(loc.longitude, loc.latitude) : null,
|
||||
visible,
|
||||
updatedAt: now
|
||||
}
|
||||
|
||||
const existed = await db.collection('locations').where({ openid: OPENID }).limit(1).get()
|
||||
if (existed.data.length) await db.collection('locations').doc(existed.data[0]._id).update({ data })
|
||||
else await db.collection('locations').add({ data })
|
||||
|
||||
return { ok: true }
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user