Files
Pawer/cloudfunctions/petDelete/index.js
2026-06-18 14:33:50 +08:00

27 lines
813 B
JavaScript

const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()
exports.main = async event => {
const { OPENID } = cloud.getWXContext()
if (!OPENID) throw new Error('no openid in wx context')
if (!event.petId) throw new Error('petId is required')
const users = await db.collection('users').where({ openid: OPENID }).limit(1).get()
if (!users.data.length) throw new Error('user not found')
const ownerId = users.data[0]._id
let pet
try {
pet = await db.collection('pets').doc(event.petId).get()
} catch (_) {
return { ok: true } // already gone
}
if (!pet.data) return { ok: true }
if (pet.data.ownerId !== ownerId) throw new Error('not allowed')
await db.collection('pets').doc(event.petId).remove()
return { ok: true }
}