33 lines
959 B
JavaScript
33 lines
959 B
JavaScript
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 { postId, liked } = event
|
|
if (!postId) throw new Error('postId is required')
|
|
|
|
const existed = await db.collection('postLikes').where({ postId, openid: OPENID }).limit(1).get()
|
|
let delta = 0
|
|
|
|
if (liked && !existed.data.length) {
|
|
await db.collection('postLikes').add({ data: { postId, openid: OPENID, createdAt: Date.now() } })
|
|
delta = 1
|
|
}
|
|
|
|
if (!liked && existed.data.length) {
|
|
await db.collection('postLikes').doc(existed.data[0]._id).remove()
|
|
delta = -1
|
|
}
|
|
|
|
if (delta) {
|
|
await db.collection('posts').doc(postId).update({ data: { 'counts.likes': _.inc(delta) } })
|
|
}
|
|
|
|
const post = await db.collection('posts').doc(postId).get()
|
|
return { liked: Boolean(liked), likes: post.data.counts?.likes || 0 }
|
|
}
|
|
|