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 { targetId } = event if (!targetId || targetId === OPENID) return { code: -1, message: '参数错误' } try { const existRes = await db.collection('follows') .where({ followerId: OPENID, followeeId: targetId }) .count() if (existRes.total > 0) { // unfollow await db.collection('follows') .where({ followerId: OPENID, followeeId: targetId }) .remove() await Promise.all([ db.collection('users').where({ openid: OPENID }).update({ data: { 'stats.friends': _.inc(-1) } }), db.collection('users').where({ openid: targetId }).update({ data: { 'stats.friends': _.inc(-1) } }), ]) return { code: 0, data: { following: false } } } else { // follow await db.collection('follows').add({ data: { followerId: OPENID, followeeId: targetId, createdAt: db.serverDate() }, }) await Promise.all([ db.collection('users').where({ openid: OPENID }).update({ data: { 'stats.friends': _.inc(1) } }), db.collection('users').where({ openid: targetId }).update({ data: { 'stats.friends': _.inc(1) } }), ]) return { code: 0, data: { following: true } } } } catch (e) { return { code: -1, message: e.message } } }