v0.0.4
This commit is contained in:
46
cloudfunctions/matchLike/index.js
Normal file
46
cloudfunctions/matchLike/index.js
Normal file
@@ -0,0 +1,46 @@
|
||||
const cloud = require('wx-server-sdk')
|
||||
|
||||
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
|
||||
const db = cloud.database()
|
||||
const _ = db.command
|
||||
|
||||
exports.main = async event => {
|
||||
const { OPENID } = cloud.getWXContext()
|
||||
const { petId } = event
|
||||
if (!petId) throw new Error('petId is required')
|
||||
|
||||
// Get current user and their pets
|
||||
const userRes = await db.collection('users').where({ openid: OPENID }).limit(1).get()
|
||||
if (!userRes.data.length) throw new Error('user not found')
|
||||
const userId = userRes.data[0]._id
|
||||
|
||||
// Record this like (idempotent)
|
||||
const existed = await db.collection('matches').where({ fromOpenid: OPENID, petId }).limit(1).get()
|
||||
if (!existed.data.length) {
|
||||
await db.collection('matches').add({ data: { fromOpenid: OPENID, userId, petId, createdAt: Date.now() } })
|
||||
}
|
||||
|
||||
// Check mutual match: does the target pet's owner like any of current user's pets?
|
||||
let matched = false
|
||||
try {
|
||||
const targetPetRes = await db.collection('pets').doc(petId).get()
|
||||
const targetOwnerId = targetPetRes.data?.ownerId
|
||||
if (targetOwnerId && targetOwnerId !== userId) {
|
||||
const targetOwnerRes = await db.collection('users').doc(targetOwnerId).get()
|
||||
const targetOpenid = targetOwnerRes.data?.openid
|
||||
if (targetOpenid) {
|
||||
const myPetsRes = await db.collection('pets').where({ ownerId: userId }).limit(20).get()
|
||||
const myPetIds = myPetsRes.data.map(p => p._id)
|
||||
if (myPetIds.length) {
|
||||
const reverseRes = await db.collection('matches')
|
||||
.where({ fromOpenid: targetOpenid, petId: _.in(myPetIds) })
|
||||
.limit(1)
|
||||
.get()
|
||||
matched = reverseRes.data.length > 0
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (_) {}
|
||||
|
||||
return { matched }
|
||||
}
|
||||
Reference in New Issue
Block a user