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>
This commit is contained in:
@@ -114,6 +114,62 @@
|
|||||||
"runtime": "Nodejs20.19",
|
"runtime": "Nodejs20.19",
|
||||||
"handler": "index.main",
|
"handler": "index.main",
|
||||||
"description": "删除宠物档案"
|
"description": "删除宠物档案"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "getMessages",
|
||||||
|
"timeout": 10,
|
||||||
|
"runtime": "Nodejs20.19",
|
||||||
|
"handler": "index.main",
|
||||||
|
"description": "获取与某用户的聊天消息列表"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "sendMessage",
|
||||||
|
"timeout": 10,
|
||||||
|
"runtime": "Nodejs20.19",
|
||||||
|
"handler": "index.main",
|
||||||
|
"description": "发送私信消息"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "getHotTopics",
|
||||||
|
"timeout": 10,
|
||||||
|
"runtime": "Nodejs20.19",
|
||||||
|
"handler": "index.main",
|
||||||
|
"description": "获取热门话题标签"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "searchPosts",
|
||||||
|
"timeout": 10,
|
||||||
|
"runtime": "Nodejs20.19",
|
||||||
|
"handler": "index.main",
|
||||||
|
"description": "搜索帖子"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "searchUsers",
|
||||||
|
"timeout": 10,
|
||||||
|
"runtime": "Nodejs20.19",
|
||||||
|
"handler": "index.main",
|
||||||
|
"description": "搜索用户"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "getStory",
|
||||||
|
"timeout": 10,
|
||||||
|
"runtime": "Nodejs20.19",
|
||||||
|
"handler": "index.main",
|
||||||
|
"description": "获取用户故事(最近带图动态)"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "getNotifications",
|
||||||
|
"timeout": 10,
|
||||||
|
"runtime": "Nodejs20.19",
|
||||||
|
"handler": "index.main",
|
||||||
|
"description": "获取通知列表(点赞/评论聚合)"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "markAllRead",
|
||||||
|
"timeout": 10,
|
||||||
|
"runtime": "Nodejs20.19",
|
||||||
|
"handler": "index.main",
|
||||||
|
"description": "标记全部通知已读"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
32
cloudfunctions/getHotTopics/index.js
Normal file
32
cloudfunctions/getHotTopics/index.js
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
const cloud = require('wx-server-sdk')
|
||||||
|
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
|
||||||
|
const db = cloud.database()
|
||||||
|
const SCAN_LIMIT = 200
|
||||||
|
const TOP_N = 10
|
||||||
|
|
||||||
|
exports.main = async (event, context) => {
|
||||||
|
try {
|
||||||
|
const res = await db.collection('posts')
|
||||||
|
.orderBy('createdAt', 'desc')
|
||||||
|
.limit(SCAN_LIMIT)
|
||||||
|
.field({ hashtags: true })
|
||||||
|
.get()
|
||||||
|
|
||||||
|
const counts = {}
|
||||||
|
res.data.forEach(p => {
|
||||||
|
;(p.hashtags || []).forEach(tag => {
|
||||||
|
if (!tag) return
|
||||||
|
counts[tag] = (counts[tag] || 0) + 1
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
const topics = Object.keys(counts)
|
||||||
|
.map(tag => ({ tag, count: counts[tag] }))
|
||||||
|
.sort((a, b) => b.count - a.count)
|
||||||
|
.slice(0, TOP_N)
|
||||||
|
|
||||||
|
return { code: 0, data: topics }
|
||||||
|
} catch (e) {
|
||||||
|
return { code: -1, message: e.message }
|
||||||
|
}
|
||||||
|
}
|
||||||
1
cloudfunctions/getHotTopics/package.json
Normal file
1
cloudfunctions/getHotTopics/package.json
Normal file
@@ -0,0 +1 @@
|
|||||||
|
{ "name": "getHotTopics", "version": "1.0.0", "main": "index.js", "dependencies": { "wx-server-sdk": "~2.1.2" } }
|
||||||
46
cloudfunctions/getMessages/index.js
Normal file
46
cloudfunctions/getMessages/index.js
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
const cloud = require('wx-server-sdk')
|
||||||
|
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
|
||||||
|
const db = cloud.database()
|
||||||
|
const _ = db.command
|
||||||
|
const PAGE_SIZE = 30
|
||||||
|
|
||||||
|
exports.main = async (event, context) => {
|
||||||
|
const { OPENID } = cloud.getWXContext()
|
||||||
|
const { peerId, page = 0 } = event || {}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const meRes = await db.collection('users').where({ openid: OPENID }).get()
|
||||||
|
if (meRes.data.length === 0) return { code: -1, message: '用户不存在' }
|
||||||
|
const myId = meRes.data[0]._id
|
||||||
|
|
||||||
|
let list = []
|
||||||
|
if (peerId) {
|
||||||
|
const skip = page * PAGE_SIZE
|
||||||
|
const msgRes = await db.collection('messages')
|
||||||
|
.where(_.or([
|
||||||
|
{ fromId: myId, toId: peerId },
|
||||||
|
{ fromId: peerId, toId: myId },
|
||||||
|
]))
|
||||||
|
.orderBy('createdAt', 'desc')
|
||||||
|
.skip(skip)
|
||||||
|
.limit(PAGE_SIZE)
|
||||||
|
.get()
|
||||||
|
|
||||||
|
list = msgRes.data.reverse().map(m => ({ ...m, isMe: m.fromId === myId }))
|
||||||
|
|
||||||
|
// 把对方发来的未读消息标记为已读
|
||||||
|
const unreadIds = msgRes.data.filter(m => m.toId === myId && !m.isRead).map(m => m._id)
|
||||||
|
if (unreadIds.length) {
|
||||||
|
await db.collection('messages').where({ _id: _.in(unreadIds) }).update({ data: { isRead: true } })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const unreadRes = await db.collection('messages')
|
||||||
|
.where({ toId: myId, isRead: _.neq(true) })
|
||||||
|
.count()
|
||||||
|
|
||||||
|
return { code: 0, data: { list, unreadCount: unreadRes.total } }
|
||||||
|
} catch (e) {
|
||||||
|
return { code: -1, message: e.message }
|
||||||
|
}
|
||||||
|
}
|
||||||
1
cloudfunctions/getMessages/package.json
Normal file
1
cloudfunctions/getMessages/package.json
Normal file
@@ -0,0 +1 @@
|
|||||||
|
{ "name": "getMessages", "version": "1.0.0", "main": "index.js", "dependencies": { "wx-server-sdk": "~2.1.2" } }
|
||||||
80
cloudfunctions/getNotifications/index.js
Normal file
80
cloudfunctions/getNotifications/index.js
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
const cloud = require('wx-server-sdk')
|
||||||
|
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
|
||||||
|
const db = cloud.database()
|
||||||
|
const _ = db.command
|
||||||
|
|
||||||
|
// 项目暂未建立独立的通知集合,这里通过聚合"我的动态"收到的点赞 / 评论
|
||||||
|
// 实时合成通知列表;已读状态通过用户文档上的 lastReadNotificationsAt 时间戳比对得出
|
||||||
|
exports.main = async (event, context) => {
|
||||||
|
const { OPENID } = cloud.getWXContext()
|
||||||
|
|
||||||
|
try {
|
||||||
|
const meRes = await db.collection('users').where({ openid: OPENID }).get()
|
||||||
|
if (meRes.data.length === 0) return { code: 0, data: [] }
|
||||||
|
const me = meRes.data[0]
|
||||||
|
const lastRead = me.lastReadNotificationsAt ? new Date(me.lastReadNotificationsAt).getTime() : 0
|
||||||
|
|
||||||
|
const myPostsRes = await db.collection('posts')
|
||||||
|
.where({ authorId: OPENID })
|
||||||
|
.field({ _id: true })
|
||||||
|
.orderBy('createdAt', 'desc')
|
||||||
|
.limit(50)
|
||||||
|
.get()
|
||||||
|
const myPostIds = myPostsRes.data.map(p => p._id)
|
||||||
|
|
||||||
|
const items = []
|
||||||
|
|
||||||
|
if (myPostIds.length) {
|
||||||
|
const [likesRes, commentsRes] = await Promise.all([
|
||||||
|
db.collection('likes')
|
||||||
|
.where({ postId: _.in(myPostIds), userId: _.neq(OPENID) })
|
||||||
|
.orderBy('createdAt', 'desc')
|
||||||
|
.limit(20)
|
||||||
|
.get(),
|
||||||
|
db.collection('comments')
|
||||||
|
.where({ postId: _.in(myPostIds), authorId: _.neq(OPENID) })
|
||||||
|
.orderBy('createdAt', 'desc')
|
||||||
|
.limit(20)
|
||||||
|
.get(),
|
||||||
|
])
|
||||||
|
|
||||||
|
likesRes.data.forEach(l => items.push({
|
||||||
|
_id: `like_${l._id}`,
|
||||||
|
fromId: l.userId,
|
||||||
|
postId: l.postId,
|
||||||
|
action: '点赞',
|
||||||
|
target: '动态',
|
||||||
|
createdAt: l.createdAt,
|
||||||
|
}))
|
||||||
|
|
||||||
|
commentsRes.data.forEach(c => items.push({
|
||||||
|
_id: `comment_${c._id}`,
|
||||||
|
fromId: c.authorId,
|
||||||
|
postId: c.postId,
|
||||||
|
action: '评论',
|
||||||
|
target: '动态',
|
||||||
|
createdAt: c.createdAt,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
items.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
|
||||||
|
const sliced = items.slice(0, 30)
|
||||||
|
|
||||||
|
const fromIds = [...new Set(sliced.map(i => i.fromId).filter(Boolean))]
|
||||||
|
const usersRes = fromIds.length
|
||||||
|
? await db.collection('users').where({ openid: _.in(fromIds) }).field({ openid: true, nickName: true }).get()
|
||||||
|
: { data: [] }
|
||||||
|
const nickMap = {}
|
||||||
|
usersRes.data.forEach(u => { nickMap[u.openid] = u.nickName })
|
||||||
|
|
||||||
|
const result = sliced.map(i => ({
|
||||||
|
...i,
|
||||||
|
fromNick: nickMap[i.fromId] || '一位用户',
|
||||||
|
isRead: new Date(i.createdAt).getTime() <= lastRead,
|
||||||
|
}))
|
||||||
|
|
||||||
|
return { code: 0, data: result }
|
||||||
|
} catch (e) {
|
||||||
|
return { code: -1, message: e.message }
|
||||||
|
}
|
||||||
|
}
|
||||||
1
cloudfunctions/getNotifications/package.json
Normal file
1
cloudfunctions/getNotifications/package.json
Normal file
@@ -0,0 +1 @@
|
|||||||
|
{ "name": "getNotifications", "version": "1.0.0", "main": "index.js", "dependencies": { "wx-server-sdk": "~2.1.2" } }
|
||||||
51
cloudfunctions/getStory/index.js
Normal file
51
cloudfunctions/getStory/index.js
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
const cloud = require('wx-server-sdk')
|
||||||
|
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
|
||||||
|
const db = cloud.database()
|
||||||
|
const _ = db.command
|
||||||
|
const ONE_DAY_MS = 24 * 3600 * 1000
|
||||||
|
|
||||||
|
// 项目暂未建立独立的"故事"集合,这里把指定用户最近(24小时内)发布的
|
||||||
|
// 带图片动态包装成"故事"展示,作为 Stories 功能的轻量实现
|
||||||
|
exports.main = async (event, context) => {
|
||||||
|
const id = (event && event.id) || ''
|
||||||
|
if (!id) return { code: -1, message: '缺少用户ID' }
|
||||||
|
|
||||||
|
try {
|
||||||
|
const since = new Date(Date.now() - ONE_DAY_MS)
|
||||||
|
let postsRes = await db.collection('posts')
|
||||||
|
.where({ authorId: id, createdAt: _.gte(since) })
|
||||||
|
.orderBy('createdAt', 'desc')
|
||||||
|
.limit(20)
|
||||||
|
.get()
|
||||||
|
|
||||||
|
let posts = postsRes.data.filter(p => Array.isArray(p.images) && p.images.length > 0)
|
||||||
|
|
||||||
|
if (posts.length === 0) {
|
||||||
|
// 兜底:取该用户最近一条带图动态
|
||||||
|
const fallbackRes = await db.collection('posts')
|
||||||
|
.where({ authorId: id })
|
||||||
|
.orderBy('createdAt', 'desc')
|
||||||
|
.limit(20)
|
||||||
|
.get()
|
||||||
|
posts = fallbackRes.data.filter(p => Array.isArray(p.images) && p.images.length > 0).slice(0, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (posts.length === 0) return { code: 0, data: [] }
|
||||||
|
|
||||||
|
const userRes = await db.collection('users').where({ openid: id }).field({ nickName: true }).get()
|
||||||
|
const authorName = (userRes.data[0] && userRes.data[0].nickName) || '宠物爱好者'
|
||||||
|
|
||||||
|
const stories = posts.map(p => ({
|
||||||
|
_id: p._id,
|
||||||
|
authorId: p.authorId,
|
||||||
|
authorName,
|
||||||
|
imageUrl: p.images[0],
|
||||||
|
text: p.content || '',
|
||||||
|
createdAt: p.createdAt,
|
||||||
|
}))
|
||||||
|
|
||||||
|
return { code: 0, data: stories }
|
||||||
|
} catch (e) {
|
||||||
|
return { code: -1, message: e.message }
|
||||||
|
}
|
||||||
|
}
|
||||||
1
cloudfunctions/getStory/package.json
Normal file
1
cloudfunctions/getStory/package.json
Normal file
@@ -0,0 +1 @@
|
|||||||
|
{ "name": "getStory", "version": "1.0.0", "main": "index.js", "dependencies": { "wx-server-sdk": "~2.1.2" } }
|
||||||
19
cloudfunctions/markAllRead/index.js
Normal file
19
cloudfunctions/markAllRead/index.js
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
const cloud = require('wx-server-sdk')
|
||||||
|
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
|
||||||
|
const db = cloud.database()
|
||||||
|
|
||||||
|
// 与 getNotifications 配套:把"已读截止时间"写到用户文档上,
|
||||||
|
// 之后凡是早于该时间的通知都视为已读
|
||||||
|
exports.main = async (event, context) => {
|
||||||
|
const { OPENID } = cloud.getWXContext()
|
||||||
|
|
||||||
|
try {
|
||||||
|
await db.collection('users')
|
||||||
|
.where({ openid: OPENID })
|
||||||
|
.update({ data: { lastReadNotificationsAt: db.serverDate() } })
|
||||||
|
|
||||||
|
return { code: 0, data: null }
|
||||||
|
} catch (e) {
|
||||||
|
return { code: -1, message: e.message }
|
||||||
|
}
|
||||||
|
}
|
||||||
1
cloudfunctions/markAllRead/package.json
Normal file
1
cloudfunctions/markAllRead/package.json
Normal file
@@ -0,0 +1 @@
|
|||||||
|
{ "name": "markAllRead", "version": "1.0.0", "main": "index.js", "dependencies": { "wx-server-sdk": "~2.1.2" } }
|
||||||
52
cloudfunctions/searchPosts/index.js
Normal file
52
cloudfunctions/searchPosts/index.js
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
const cloud = require('wx-server-sdk')
|
||||||
|
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
|
||||||
|
const db = cloud.database()
|
||||||
|
const _ = db.command
|
||||||
|
const RESULT_LIMIT = 20
|
||||||
|
|
||||||
|
function escapeRegExp(s) {
|
||||||
|
return String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||||
|
}
|
||||||
|
|
||||||
|
exports.main = async (event, context) => {
|
||||||
|
const { OPENID } = cloud.getWXContext()
|
||||||
|
const keyword = String((event && event.keyword) || '').trim()
|
||||||
|
if (!keyword) return { code: 0, data: [] }
|
||||||
|
|
||||||
|
try {
|
||||||
|
const re = db.RegExp({ regexp: escapeRegExp(keyword), options: 'i' })
|
||||||
|
const postsRes = await db.collection('posts')
|
||||||
|
.where(_.or([{ content: re }, { hashtags: keyword }]))
|
||||||
|
.orderBy('createdAt', 'desc')
|
||||||
|
.limit(RESULT_LIMIT)
|
||||||
|
.get()
|
||||||
|
|
||||||
|
const posts = postsRes.data
|
||||||
|
if (posts.length === 0) return { code: 0, data: [] }
|
||||||
|
|
||||||
|
const authorIds = [...new Set(posts.map(p => p.authorId))]
|
||||||
|
const authorsRes = await db.collection('users')
|
||||||
|
.where({ openid: _.in(authorIds) })
|
||||||
|
.field({ nickName: true, avatarUrl: true, openid: true, pets: true, location: true })
|
||||||
|
.get()
|
||||||
|
const authorMap = {}
|
||||||
|
authorsRes.data.forEach(u => { authorMap[u.openid] = u })
|
||||||
|
|
||||||
|
const postIds = posts.map(p => p._id)
|
||||||
|
const likesRes = await db.collection('likes')
|
||||||
|
.where({ userId: OPENID, postId: _.in(postIds) })
|
||||||
|
.field({ postId: true })
|
||||||
|
.get()
|
||||||
|
const likedSet = new Set(likesRes.data.map(l => l.postId))
|
||||||
|
|
||||||
|
const enriched = posts.map(p => ({
|
||||||
|
...p,
|
||||||
|
author: authorMap[p.authorId] || null,
|
||||||
|
isLiked: likedSet.has(p._id),
|
||||||
|
}))
|
||||||
|
|
||||||
|
return { code: 0, data: enriched }
|
||||||
|
} catch (e) {
|
||||||
|
return { code: -1, message: e.message }
|
||||||
|
}
|
||||||
|
}
|
||||||
1
cloudfunctions/searchPosts/package.json
Normal file
1
cloudfunctions/searchPosts/package.json
Normal file
@@ -0,0 +1 @@
|
|||||||
|
{ "name": "searchPosts", "version": "1.0.0", "main": "index.js", "dependencies": { "wx-server-sdk": "~2.1.2" } }
|
||||||
27
cloudfunctions/searchUsers/index.js
Normal file
27
cloudfunctions/searchUsers/index.js
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
const cloud = require('wx-server-sdk')
|
||||||
|
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
|
||||||
|
const db = cloud.database()
|
||||||
|
const _ = db.command
|
||||||
|
const RESULT_LIMIT = 20
|
||||||
|
|
||||||
|
function escapeRegExp(s) {
|
||||||
|
return String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||||
|
}
|
||||||
|
|
||||||
|
exports.main = async (event, context) => {
|
||||||
|
const keyword = String((event && event.keyword) || '').trim()
|
||||||
|
if (!keyword) return { code: 0, data: [] }
|
||||||
|
|
||||||
|
try {
|
||||||
|
const re = db.RegExp({ regexp: escapeRegExp(keyword), options: 'i' })
|
||||||
|
const res = await db.collection('users')
|
||||||
|
.where(_.or([{ nickName: re }, { handle: re }, { location: re }]))
|
||||||
|
.field({ nickName: true, avatarUrl: true, bio: true, handle: true, location: true })
|
||||||
|
.limit(RESULT_LIMIT)
|
||||||
|
.get()
|
||||||
|
|
||||||
|
return { code: 0, data: res.data }
|
||||||
|
} catch (e) {
|
||||||
|
return { code: -1, message: e.message }
|
||||||
|
}
|
||||||
|
}
|
||||||
1
cloudfunctions/searchUsers/package.json
Normal file
1
cloudfunctions/searchUsers/package.json
Normal file
@@ -0,0 +1 @@
|
|||||||
|
{ "name": "searchUsers", "version": "1.0.0", "main": "index.js", "dependencies": { "wx-server-sdk": "~2.1.2" } }
|
||||||
32
cloudfunctions/sendMessage/index.js
Normal file
32
cloudfunctions/sendMessage/index.js
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
const cloud = require('wx-server-sdk')
|
||||||
|
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
|
||||||
|
const db = cloud.database()
|
||||||
|
|
||||||
|
exports.main = async (event, context) => {
|
||||||
|
const { OPENID } = cloud.getWXContext()
|
||||||
|
const { toId, content, type = 'text' } = event || {}
|
||||||
|
|
||||||
|
if (!toId || !String(content || '').trim()) {
|
||||||
|
return { code: -1, message: '参数错误' }
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const meRes = await db.collection('users').where({ openid: OPENID }).get()
|
||||||
|
if (meRes.data.length === 0) return { code: -1, message: '用户不存在' }
|
||||||
|
const myId = meRes.data[0]._id
|
||||||
|
|
||||||
|
const message = {
|
||||||
|
fromId: myId,
|
||||||
|
toId,
|
||||||
|
content: String(content).trim(),
|
||||||
|
type,
|
||||||
|
isRead: false,
|
||||||
|
createdAt: db.serverDate(),
|
||||||
|
}
|
||||||
|
const res = await db.collection('messages').add({ data: message })
|
||||||
|
|
||||||
|
return { code: 0, data: { _id: res._id, ...message } }
|
||||||
|
} catch (e) {
|
||||||
|
return { code: -1, message: e.message }
|
||||||
|
}
|
||||||
|
}
|
||||||
1
cloudfunctions/sendMessage/package.json
Normal file
1
cloudfunctions/sendMessage/package.json
Normal file
@@ -0,0 +1 @@
|
|||||||
|
{ "name": "sendMessage", "version": "1.0.0", "main": "index.js", "dependencies": { "wx-server-sdk": "~2.1.2" } }
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { UserProfile, GeoPoint, AppGlobalData } from './types/index'
|
import { AppGlobalData } from './types/index'
|
||||||
import { getCachedUser, login } from './utils/auth'
|
import { getCachedUser } from './utils/auth'
|
||||||
import { CLOUD_ENV, HEARTBEAT_INTERVAL_MS } from './utils/constants'
|
import { CLOUD_ENV, HEARTBEAT_INTERVAL_MS } from './utils/constants'
|
||||||
import { api } from './utils/api'
|
import { api } from './utils/api'
|
||||||
|
|
||||||
@@ -44,16 +44,6 @@ App<{ globalData: AppGlobalData }>({
|
|||||||
this._stopLocationHeartbeat()
|
this._stopLocationHeartbeat()
|
||||||
},
|
},
|
||||||
|
|
||||||
async _initLogin() {
|
|
||||||
try {
|
|
||||||
const userInfo = await login()
|
|
||||||
this.globalData.userInfo = userInfo
|
|
||||||
this.globalData.isLoggedIn = true
|
|
||||||
} catch (e) {
|
|
||||||
console.error('Login failed', e)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
_initLocation() {
|
_initLocation() {
|
||||||
wx.getLocation({
|
wx.getLocation({
|
||||||
type: 'gcj02',
|
type: 'gcj02',
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ Page({
|
|||||||
onLoad(query: { userId?: string }) {
|
onLoad(query: { userId?: string }) {
|
||||||
const info = wx.getSystemInfoSync()
|
const info = wx.getSystemInfoSync()
|
||||||
this.setData({ statusBarHeight: info.statusBarHeight, peerId: query.userId || '' })
|
this.setData({ statusBarHeight: info.statusBarHeight, peerId: query.userId || '' })
|
||||||
|
this.loadPeerInfo()
|
||||||
this.loadMessages()
|
this.loadMessages()
|
||||||
this.subscribeRealtime()
|
this.subscribeRealtime()
|
||||||
},
|
},
|
||||||
@@ -26,9 +27,18 @@ Page({
|
|||||||
this._watcher?.close()
|
this._watcher?.close()
|
||||||
},
|
},
|
||||||
|
|
||||||
async loadMessages() {
|
async loadPeerInfo() {
|
||||||
|
if (!this.data.peerId) return
|
||||||
try {
|
try {
|
||||||
const res = await api.getMessages()
|
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) => ({
|
const msgs = res.list.map((m: any) => ({
|
||||||
...m,
|
...m,
|
||||||
isMe: m.fromId === app.globalData?.userInfo?._id,
|
isMe: m.fromId === app.globalData?.userInfo?._id,
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { api } from '../../utils/api'
|
||||||
import { getAvatarGradient, formatTime } from '../../utils/format'
|
import { getAvatarGradient, formatTime } from '../../utils/format'
|
||||||
|
|
||||||
Page({
|
Page({
|
||||||
@@ -11,13 +12,13 @@ Page({
|
|||||||
|
|
||||||
async loadNotifications() {
|
async loadNotifications() {
|
||||||
try {
|
try {
|
||||||
const res = await wx.cloud.callFunction({ name: 'getNotifications', data: {} }) as any
|
const list = await api.getNotifications()
|
||||||
const list = (res.result?.data || []).map((n: any) => ({
|
const enriched = (list || []).map((n: any) => ({
|
||||||
...n,
|
...n,
|
||||||
gradient: getAvatarGradient(n.fromId || ''),
|
gradient: getAvatarGradient(n.fromId || ''),
|
||||||
timeText: formatTime(n.createdAt),
|
timeText: formatTime(n.createdAt),
|
||||||
}))
|
}))
|
||||||
this.setData({ list })
|
this.setData({ list: enriched })
|
||||||
} catch {}
|
} catch {}
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -27,7 +28,7 @@ Page({
|
|||||||
},
|
},
|
||||||
|
|
||||||
onReadAll() {
|
onReadAll() {
|
||||||
wx.cloud.callFunction({ name: 'markAllRead', data: {} }).catch(() => {})
|
api.markAllRead().catch(() => {})
|
||||||
const list = this.data.list.map((n: any) => ({ ...n, isRead: true }))
|
const list = this.data.list.map((n: any) => ({ ...n, isRead: true }))
|
||||||
this.setData({ list })
|
this.setData({ list })
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { api } from '../../utils/api'
|
||||||
import { getAvatarGradient } from '../../utils/format'
|
import { getAvatarGradient } from '../../utils/format'
|
||||||
|
|
||||||
Page({
|
Page({
|
||||||
@@ -19,8 +20,8 @@ Page({
|
|||||||
|
|
||||||
async loadHotTopics() {
|
async loadHotTopics() {
|
||||||
try {
|
try {
|
||||||
const res = await wx.cloud.callFunction({ name: 'getHotTopics', data: {} }) as any
|
const topics = await api.getHotTopics()
|
||||||
this.setData({ hotTopics: res.result?.data || [] })
|
this.setData({ hotTopics: topics || [] })
|
||||||
} catch {}
|
} catch {}
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -38,12 +39,12 @@ Page({
|
|||||||
this.setData({ loading: true })
|
this.setData({ loading: true })
|
||||||
try {
|
try {
|
||||||
const [posts, users] = await Promise.all([
|
const [posts, users] = await Promise.all([
|
||||||
wx.cloud.callFunction({ name: 'searchPosts', data: { keyword: kw } }) as any,
|
api.searchPosts(kw),
|
||||||
wx.cloud.callFunction({ name: 'searchUsers', data: { keyword: kw } }) as any,
|
api.searchUsers(kw),
|
||||||
])
|
])
|
||||||
this.setData({
|
this.setData({
|
||||||
postResults: posts.result?.data || [],
|
postResults: posts || [],
|
||||||
userResults: (users.result?.data || []).map((u: any) => ({
|
userResults: (users || []).map((u: any) => ({
|
||||||
...u,
|
...u,
|
||||||
gradient: getAvatarGradient(u._id),
|
gradient: getAvatarGradient(u._id),
|
||||||
})),
|
})),
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { api } from '../../utils/api'
|
||||||
import { getAvatarGradient, formatTime } from '../../utils/format'
|
import { getAvatarGradient, formatTime } from '../../utils/format'
|
||||||
|
|
||||||
const DURATION = 5000
|
const DURATION = 5000
|
||||||
@@ -22,15 +23,18 @@ Page({
|
|||||||
|
|
||||||
async loadStory(id: string) {
|
async loadStory(id: string) {
|
||||||
try {
|
try {
|
||||||
const res = await wx.cloud.callFunction({ name: 'getStory', data: { id } }) as any
|
const list = await api.getStory(id)
|
||||||
const stories = (res.result?.data || []).map((s: any) => ({
|
const stories = (list || []).map((s: any) => ({
|
||||||
...s,
|
...s,
|
||||||
gradient: getAvatarGradient(s.authorId),
|
gradient: getAvatarGradient(s.authorId),
|
||||||
timeText: formatTime(s.createdAt),
|
timeText: formatTime(s.createdAt),
|
||||||
}))
|
}))
|
||||||
this.setData({ stories, currentStory: stories[0] || {} })
|
this.setData({ stories, currentStory: stories[0] || {} })
|
||||||
this.startProgress()
|
if (stories.length) this.startProgress()
|
||||||
} catch {}
|
else wx.navigateBack()
|
||||||
|
} catch {
|
||||||
|
wx.navigateBack()
|
||||||
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
startProgress() {
|
startProgress() {
|
||||||
|
|||||||
@@ -71,17 +71,6 @@ export interface Comment {
|
|||||||
createdAt: string
|
createdAt: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Message {
|
|
||||||
_id: string
|
|
||||||
fromId: string
|
|
||||||
from?: UserProfile
|
|
||||||
toId: string
|
|
||||||
content: string
|
|
||||||
type: 'greeting' | 'text' | 'image'
|
|
||||||
isRead: boolean
|
|
||||||
createdAt: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface NearbyUser {
|
export interface NearbyUser {
|
||||||
userId: string
|
userId: string
|
||||||
user: UserProfile
|
user: UserProfile
|
||||||
@@ -93,14 +82,6 @@ export interface NearbyUser {
|
|||||||
location: GeoPoint
|
location: GeoPoint
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface TabBarItem {
|
|
||||||
pagePath: string
|
|
||||||
text: string
|
|
||||||
icon: string
|
|
||||||
activeIcon: string
|
|
||||||
selected: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface NavBarInfo {
|
export interface NavBarInfo {
|
||||||
statusBarHeight: number
|
statusBarHeight: number
|
||||||
navbarHeight: number
|
navbarHeight: number
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { Post, UserProfile, NearbyUser, Pet } from '../types/index'
|
import { Post, UserProfile, NearbyUser, Pet, Comment } from '../types/index'
|
||||||
|
|
||||||
type CloudResult<T> = { result: { code: number; data: T; message?: string } }
|
type CloudResult<T> = { result: { code: number; data: T; message?: string } }
|
||||||
|
|
||||||
@@ -31,9 +31,6 @@ export const api = {
|
|||||||
petId?: string
|
petId?: string
|
||||||
}) => call<Post>('createPost', params),
|
}) => call<Post>('createPost', params),
|
||||||
|
|
||||||
deletePost: (postId: string) =>
|
|
||||||
call<void>('deletePost', { postId }),
|
|
||||||
|
|
||||||
likePost: (postId: string) =>
|
likePost: (postId: string) =>
|
||||||
call<{ liked: boolean; count: number }>('likePost', { postId }),
|
call<{ liked: boolean; count: number }>('likePost', { postId }),
|
||||||
|
|
||||||
@@ -58,11 +55,11 @@ export const api = {
|
|||||||
getFollowList: (type: 'following' | 'followers', userId?: string) =>
|
getFollowList: (type: 'following' | 'followers', userId?: string) =>
|
||||||
call<UserProfile[]>('getFollowList', { type, userId }),
|
call<UserProfile[]>('getFollowList', { type, userId }),
|
||||||
|
|
||||||
getMessages: (page = 0) =>
|
getMessages: (peerId: string, page = 0) =>
|
||||||
call<{ list: any[]; unreadCount: number }>('getMessages', { page }),
|
call<{ list: any[]; unreadCount: number }>('getMessages', { peerId, page }),
|
||||||
|
|
||||||
sendMessage: (toId: string, content: string, type = 'text') =>
|
sendMessage: (toId: string, content: string, type = 'text') =>
|
||||||
call<void>('sendMessage', { toId, content, type }),
|
call<{ _id: string }>('sendMessage', { toId, content, type }),
|
||||||
|
|
||||||
updatePet: (pet: Partial<Pet> & { _id?: string }) =>
|
updatePet: (pet: Partial<Pet> & { _id?: string }) =>
|
||||||
call<Pet>('updatePet', { pet }),
|
call<Pet>('updatePet', { pet }),
|
||||||
@@ -70,15 +67,21 @@ export const api = {
|
|||||||
deletePet: (petId: string) =>
|
deletePet: (petId: string) =>
|
||||||
call<void>('deletePet', { petId }),
|
call<void>('deletePet', { petId }),
|
||||||
|
|
||||||
uploadImage: async (filePath: string): Promise<string> => {
|
getHotTopics: () =>
|
||||||
const ext = filePath.split('.').pop() || 'jpg'
|
call<{ tag: string; count: number }[]>('getHotTopics'),
|
||||||
const cloudPath = `posts/${Date.now()}_${Math.random().toString(36).slice(2)}.${ext}`
|
|
||||||
const res = await wx.cloud.uploadFile({ cloudPath, filePath })
|
|
||||||
return res.fileID
|
|
||||||
},
|
|
||||||
|
|
||||||
getFileURL: async (fileID: string): Promise<string> => {
|
searchPosts: (keyword: string) =>
|
||||||
const res = await wx.cloud.getTempFileURL({ fileList: [fileID] })
|
call<Post[]>('searchPosts', { keyword }),
|
||||||
return res.fileList[0]?.tempFileURL || fileID
|
|
||||||
},
|
searchUsers: (keyword: string) =>
|
||||||
|
call<UserProfile[]>('searchUsers', { keyword }),
|
||||||
|
|
||||||
|
getStory: (id: string) =>
|
||||||
|
call<any[]>('getStory', { id }),
|
||||||
|
|
||||||
|
getNotifications: () =>
|
||||||
|
call<any[]>('getNotifications'),
|
||||||
|
|
||||||
|
markAllRead: () =>
|
||||||
|
call<void>('markAllRead'),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import { UserProfile } from '../types/index'
|
import { UserProfile } from '../types/index'
|
||||||
import { api } from './api'
|
import { api } from './api'
|
||||||
|
|
||||||
const TOKEN_KEY = 'wangquan_token'
|
|
||||||
const USER_KEY = 'wangquan_user'
|
const USER_KEY = 'wangquan_user'
|
||||||
|
|
||||||
export async function login(): Promise<UserProfile> {
|
export async function login(): Promise<UserProfile> {
|
||||||
@@ -19,11 +18,6 @@ export function getCachedUser(): UserProfile | null {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function clearAuth(): void {
|
|
||||||
wx.removeStorageSync(TOKEN_KEY)
|
|
||||||
wx.removeStorageSync(USER_KEY)
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function requireLocation(): Promise<{ latitude: number; longitude: number }> {
|
export async function requireLocation(): Promise<{ latitude: number; longitude: number }> {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
wx.getLocation({
|
wx.getLocation({
|
||||||
|
|||||||
@@ -1,28 +1,5 @@
|
|||||||
export const CLOUD_ENV = 'cloud1-d4g697lte499543d8'
|
export const CLOUD_ENV = 'cloud1-d4g697lte499543d8'
|
||||||
|
|
||||||
export const COLORS = {
|
|
||||||
pink: '#ff4f91',
|
|
||||||
orange: '#ff9f1c',
|
|
||||||
yellow: '#ffe15a',
|
|
||||||
green: '#2fd37a',
|
|
||||||
mint: '#67e8c9',
|
|
||||||
blue: '#4d8dff',
|
|
||||||
violet: '#8c5cff',
|
|
||||||
ink: '#272235',
|
|
||||||
bgPrimary: '#fff9fb',
|
|
||||||
textPrimary: '#272235',
|
|
||||||
textSecondary: '#6a6178',
|
|
||||||
textTertiary: '#9b8fa8',
|
|
||||||
}
|
|
||||||
|
|
||||||
export const AVATAR_GRADIENTS = [
|
|
||||||
'linear-gradient(135deg, #ffd6e8, #fff1a6)',
|
|
||||||
'linear-gradient(135deg, #ffe7a0, #b7f4d2)',
|
|
||||||
'linear-gradient(135deg, #c9f7df, #d9d2ff)',
|
|
||||||
'linear-gradient(135deg, #cfe8ff, #ffd6e8)',
|
|
||||||
'linear-gradient(135deg, #e3d8ff, #ffd6e8)',
|
|
||||||
]
|
|
||||||
|
|
||||||
export const MOOD_OPTIONS = [
|
export const MOOD_OPTIONS = [
|
||||||
{ label: '开心 😄', value: 'happy' },
|
{ label: '开心 😄', value: 'happy' },
|
||||||
{ label: '累了 😮💨', value: 'tired' },
|
{ label: '累了 😮💨', value: 'tired' },
|
||||||
|
|||||||
@@ -61,12 +61,3 @@ export function getPetEmoji(species: string, breed?: string): string {
|
|||||||
}
|
}
|
||||||
return (breed && dogBreedEmoji[breed]) || '🐶'
|
return (breed && dogBreedEmoji[breed]) || '🐶'
|
||||||
}
|
}
|
||||||
|
|
||||||
export function calcDistance(lat1: number, lng1: number, lat2: number, lng2: number): number {
|
|
||||||
const R = 6371000
|
|
||||||
const dLat = (lat2 - lat1) * Math.PI / 180
|
|
||||||
const dLng = (lng2 - lng1) * Math.PI / 180
|
|
||||||
const a = Math.sin(dLat / 2) ** 2 +
|
|
||||||
Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * Math.sin(dLng / 2) ** 2
|
|
||||||
return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
|
|
||||||
}
|
|
||||||
|
|||||||
Reference in New Issue
Block a user