48 lines
1.6 KiB
JavaScript
48 lines
1.6 KiB
JavaScript
const cloud = require('wx-server-sdk')
|
|
|
|
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
|
|
const db = cloud.database()
|
|
|
|
exports.main = async event => {
|
|
const { OPENID } = cloud.getWXContext()
|
|
if (!OPENID) throw new Error('no openid in wx context')
|
|
const { targetUserId, follow } = event
|
|
if (!targetUserId) throw new Error('targetUserId is required')
|
|
|
|
const meRes = await db.collection('users').where({ openid: OPENID }).limit(1).get()
|
|
if (!meRes.data.length) throw new Error('user not found')
|
|
const meId = meRes.data[0]._id
|
|
if (meId === targetUserId) throw new Error('cannot follow yourself')
|
|
|
|
const targetRes = await db.collection('users').doc(targetUserId).get().catch(() => null)
|
|
const target = targetRes && targetRes.data
|
|
if (!target) throw new Error('target user not found')
|
|
|
|
const existing = await db.collection('follows')
|
|
.where({ followerId: meId, followeeId: targetUserId })
|
|
.limit(1)
|
|
.get()
|
|
|
|
if (follow && !existing.data.length) {
|
|
await db.collection('follows').add({
|
|
data: {
|
|
followerId: meId,
|
|
followerOpenid: OPENID,
|
|
followeeId: targetUserId,
|
|
followeeOpenid: target.openid,
|
|
createdAt: Date.now()
|
|
}
|
|
})
|
|
} else if (!follow && existing.data.length) {
|
|
await db.collection('follows').doc(existing.data[0]._id).remove()
|
|
}
|
|
|
|
// A friendship (汪友) is a mutual follow.
|
|
const back = await db.collection('follows')
|
|
.where({ followerId: targetUserId, followeeId: meId })
|
|
.limit(1)
|
|
.get()
|
|
|
|
return { following: Boolean(follow), mutual: Boolean(follow) && back.data.length > 0 }
|
|
}
|