修复动态发布与互动问题

This commit is contained in:
2026-06-23 18:43:03 +08:00
parent 702b578e1e
commit cda8685956
151 changed files with 4993 additions and 914 deletions

View File

@@ -3,6 +3,7 @@ const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()
const _ = db.command
const SERVER_MESSAGE_LIMIT = 50
function timeText(ts) {
if (!ts) return ''
@@ -18,12 +19,30 @@ async function userToPeer(u) {
return { id: u._id, name: u.nickname || '用户', avatarKey: u.avatarKey || 'gradient-avatar-1', avatarUrl: u.avatarUrl || '' }
}
function normalizeLimit(value) {
const limit = Number(value || SERVER_MESSAGE_LIMIT)
if (!Number.isFinite(limit)) return SERVER_MESSAGE_LIMIT
return Math.max(1, Math.min(Math.floor(limit), SERVER_MESSAGE_LIMIT))
}
function messageToClient(m, openid) {
return {
_id: m._id,
fromMe: m.fromOpenid === openid,
content: m.content,
type: m.type || 'text',
createdAt: m.createdAt,
timeText: timeText(m.createdAt)
}
}
exports.main = async event => {
const { OPENID } = cloud.getWXContext()
if (!OPENID) throw new Error('no openid in wx context')
let convId = event.conversationId || ''
let peer = null
const pageSize = normalizeLimit(event.pageSize || event.limit)
// Open by target user — resolve peer and find an existing conversation.
if (!convId && event.targetUserId) {
@@ -56,27 +75,32 @@ exports.main = async event => {
}
let messages = []
let nextCursor = ''
if (convId) {
const query = { conversationId: convId }
const cursor = Number(event.cursor || 0)
if (Number.isFinite(cursor) && cursor > 0) query.createdAt = _.lt(cursor)
const res = await db.collection('messages')
.where({ conversationId: convId })
.where(query)
.orderBy('createdAt', 'desc')
.limit(50)
.limit(pageSize + 1)
.get()
.catch(() => ({ data: [] }))
messages = res.data.reverse().map(m => ({
_id: m._id,
fromMe: m.fromOpenid === OPENID,
content: m.content,
type: m.type || 'text',
createdAt: m.createdAt,
timeText: timeText(m.createdAt)
}))
const page = res.data.slice(0, pageSize)
messages = page.reverse().map(m => messageToClient(m, OPENID))
if (res.data.length > pageSize && messages[0]) {
nextCursor = String(messages[0].createdAt || '')
}
// Mark this conversation read for me.
await db.collection('conversations').doc(convId).update({
data: { unreadOpenids: _.pull(OPENID), [`unreadCounts.${OPENID}`]: 0 }
}).catch(() => {})
// Mark this conversation read for me only when the client asks for it.
// Silent polling and loading older history should not write the conversation.
if (event.markRead !== false) {
await db.collection('conversations').doc(convId).update({
data: { unreadOpenids: _.pull(OPENID), [`unreadCounts.${OPENID}`]: 0 }
}).catch(() => {})
}
}
return { conversationId: convId, peer, messages }
return { conversationId: convId, peer, messages, nextCursor }
}