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, content } = event if (!postId || !content?.trim()) { return { code: -1, message: '参数错误' } } try { const postRes = await db.collection('posts').doc(postId).get().catch(() => null) if (!postRes?.data) return { code: -1, message: '帖子不存在' } const comment = { postId, authorId: OPENID, content: content.trim(), likeCount: 0, createdAt: db.serverDate(), } const res = await db.collection('comments').add({ data: comment }) await db.collection('posts').doc(postId).update({ data: { commentCount: _.inc(1) }, }) const authorRes = await db.collection('users') .where({ openid: OPENID }) .field({ nickName: true, avatarUrl: true, openid: true }) .get() return { code: 0, data: { _id: res._id, ...comment, author: authorRes.data[0] || null }, } } catch (e) { return { code: -1, message: e.message } } }