Files
PetCommunity/miniprogram/pages/chat/chat.ts
chenwu b02e26f602 chore: 清理冗余代码并补全私信/搜索/故事/通知功能
- 删除未使用的空组件目录、死代码导出(clearAuth/calcDistance/COLORS/
  AVATAR_GRADIENTS/Message/TabBarItem/deletePost/uploadImage/getFileURL/
  _initLogin),确保程序仍可正常运行
- 新增 8 个云函数并补全对应页面逻辑:getMessages/sendMessage(私信聊天)、
  getHotTopics/searchPosts/searchUsers(搜索)、getStory(故事,复用 posts
  集合)、getNotifications/markAllRead(基于点赞评论聚合的通知系统)
- 在 cloudbaserc.json 中注册全部新云函数,并通过 --deployMode zip 完成部署

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-07 16:27:28 +08:00

104 lines
2.5 KiB
TypeScript

import { api } from '../../utils/api'
import { AppGlobalData } from '../../types/index'
const app = getApp<{ globalData: AppGlobalData }>()
Page({
data: {
statusBarHeight: 0,
peerId: '',
peerName: '',
messages: [] as any[],
inputText: '',
scrollToMsg: '',
},
_watcher: null as any,
onLoad(query: { userId?: string }) {
const info = wx.getSystemInfoSync()
this.setData({ statusBarHeight: info.statusBarHeight, peerId: query.userId || '' })
this.loadPeerInfo()
this.loadMessages()
this.subscribeRealtime()
},
onUnload() {
this._watcher?.close()
},
async loadPeerInfo() {
if (!this.data.peerId) return
try {
const user = await api.getUserProfile(this.data.peerId)
this.setData({ peerName: user.nickName || '宠物爱好者' })
} catch {}
},
async loadMessages() {
if (!this.data.peerId) return
try {
const res = await api.getMessages(this.data.peerId)
const msgs = res.list.map((m: any) => ({
...m,
isMe: m.fromId === app.globalData?.userInfo?._id,
}))
this.setData({ messages: msgs })
this.scrollToBottom()
} catch {}
},
subscribeRealtime() {
const db = wx.cloud.database()
this._watcher = db.collection('messages')
.where({ toId: app.globalData?.userInfo?._id })
.watch({
onChange: snapshot => {
if (snapshot.type === 'add') {
const newMsgs = snapshot.docs.map((d: any) => ({ ...d, isMe: false }))
this.setData({ messages: [...this.data.messages, ...newMsgs] })
this.scrollToBottom()
}
},
onError: () => {},
})
},
scrollToBottom() {
const msgs = this.data.messages
if (msgs.length > 0) {
this.setData({ scrollToMsg: `msg-${msgs[msgs.length - 1]._id}` })
}
},
onInput(e: WechatMiniprogram.CustomEvent) {
this.setData({ inputText: e.detail.value })
},
async onSend() {
const text = this.data.inputText.trim()
if (!text) return
this.setData({ inputText: '' })
const tempMsg = {
_id: `temp_${Date.now()}`,
content: text,
isMe: true,
fromId: app.globalData?.userInfo?._id,
toId: this.data.peerId,
}
this.setData({ messages: [...this.data.messages, tempMsg] })
this.scrollToBottom()
try {
await api.sendMessage(this.data.peerId, text)
} catch {
wx.showToast({ title: '发送失败', icon: 'none' })
}
},
onBack() {
wx.navigateBack()
},
})