const cloud = require('wx-server-sdk') cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) const db = cloud.database() const _ = db.command const PAGE_SIZE = 20 exports.main = async (event, context) => { const { postId, page = 0 } = event if (!postId) return { code: -1, message: '缺少 postId' } try { const skip = page * PAGE_SIZE const [totalRes, commentsRes] = await Promise.all([ db.collection('comments').where({ postId }).count(), db.collection('comments') .where({ postId }) .orderBy('createdAt', 'asc') .skip(skip) .limit(PAGE_SIZE) .get(), ]) const comments = commentsRes.data const authorIds = [...new Set(comments.map(c => c.authorId))] let authorMap = {} if (authorIds.length > 0) { const authorsRes = await db.collection('users') .where({ openid: _.in(authorIds) }) .field({ nickName: true, avatarUrl: true, openid: true }) .get() authorsRes.data.forEach(u => { authorMap[u.openid] = u }) } return { code: 0, data: { list: comments.map(c => ({ ...c, author: authorMap[c.authorId] || null })), total: totalRes.total, }, } } catch (e) { return { code: -1, message: e.message } } }