Initial commit
This commit is contained in:
54
cloudfunctions/likePost/index.js
Normal file
54
cloudfunctions/likePost/index.js
Normal file
@@ -0,0 +1,54 @@
|
||||
const cloud = require('wx-server-sdk')
|
||||
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
|
||||
const db = cloud.database()
|
||||
const _ = db.command
|
||||
|
||||
exports.main = async (event, context) => {
|
||||
const { OPENID } = cloud.getWXContext()
|
||||
const { postId } = event
|
||||
|
||||
if (!postId) return { code: -1, message: '缺少 postId' }
|
||||
|
||||
try {
|
||||
// 检查是否已点赞
|
||||
const existRes = await db.collection('likes')
|
||||
.where({ userId: OPENID, postId })
|
||||
.get()
|
||||
|
||||
let liked
|
||||
let delta
|
||||
|
||||
if (existRes.data.length > 0) {
|
||||
// 取消点赞
|
||||
await db.collection('likes').doc(existRes.data[0]._id).remove()
|
||||
delta = -1
|
||||
liked = false
|
||||
} else {
|
||||
// 点赞
|
||||
await db.collection('likes').add({
|
||||
data: {
|
||||
userId: OPENID,
|
||||
postId,
|
||||
createdAt: db.serverDate(),
|
||||
},
|
||||
})
|
||||
delta = 1
|
||||
liked = true
|
||||
}
|
||||
|
||||
// 原子更新帖子点赞数
|
||||
await db.collection('posts').doc(postId).update({
|
||||
data: { likeCount: _.inc(delta) },
|
||||
})
|
||||
|
||||
// 获取最新计数
|
||||
const postRes = await db.collection('posts').doc(postId).field({ likeCount: true }).get()
|
||||
|
||||
return {
|
||||
code: 0,
|
||||
data: { liked, count: postRes.data.likeCount },
|
||||
}
|
||||
} catch (e) {
|
||||
return { code: -1, message: e.message }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user