Files
WoMenQuNaJu/cloudfunctions/joinRoom/index.js
2026-02-13 15:43:40 +08:00

69 lines
1.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 云函数入口文件
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 wxContext = cloud.getWXContext()
const openid = wxContext.OPENID
const { roomId, userInfo } = event
if (!roomId) {
return { success: false, msg: '缺少 roomId' }
}
try {
const roomRef = db.collection('rooms').doc(roomId)
const room = await roomRef.get()
if (!room.data) {
return { success: false, msg: '房间不存在' }
}
// 检查是否已经在房间内
const members = room.data.members || []
const isMember = members.some(m => m.openid === openid)
if (isMember) {
return { success: true, msg: '已在房间内' }
}
// 检查人数限制最多8人
if (members.length >= 8) {
return { success: false, msg: '房间人数已满最多8人' }
}
// 加入房间
const newMember = {
openid: openid,
avatarUrl: userInfo?.avatarUrl || 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
nickName: userInfo?.nickName || '微信用户',
location: null,
joinedAt: new Date()
}
await roomRef.update({
data: {
members: _.push(newMember)
}
})
}
return {
success: true,
msg: '加入成功'
}
} catch (err) {
console.error(err)
return {
success: false,
msg: '加入失败',
error: err
}
}
}