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 { content, images = [], video, location, hashtags = [], mood, petId } = event if (!content?.trim() && images.length === 0) { return { code: -1, message: '内容不能为空' } } try { const post = { authorId: OPENID, petId: petId || null, content: (content || '').trim(), images, video: video || null, location: location || null, hashtags, mood: mood || null, likeCount: 0, commentCount: 0, createdAt: db.serverDate(), updatedAt: db.serverDate(), } const res = await db.collection('posts').add({ data: post }) // 更新用户帖子统计 await db.collection('users') .where({ openid: OPENID }) .update({ data: { 'stats.posts': _.inc(1) } }) // 更新话题统计 if (hashtags.length > 0) { const batch = hashtags.map(tag => db.collection('topics') .where({ tag }) .get() .then(r => { if (r.data.length === 0) { return db.collection('topics').add({ data: { tag, count: 1, createdAt: db.serverDate() } }) } return db.collection('topics').where({ tag }).update({ data: { count: _.inc(1) } }) }) ) await Promise.all(batch).catch(() => {}) } return { code: 0, data: { _id: res._id, ...post } } } catch (e) { return { code: -1, message: e.message } } }