Initial commit
This commit is contained in:
83
cloudfunctions/getPosts/index.js
Normal file
83
cloudfunctions/getPosts/index.js
Normal file
@@ -0,0 +1,83 @@
|
||||
const cloud = require('wx-server-sdk')
|
||||
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
|
||||
const db = cloud.database()
|
||||
const _ = db.command
|
||||
const PAGE_SIZE = 10
|
||||
|
||||
exports.main = async (event, context) => {
|
||||
const { OPENID } = cloud.getWXContext()
|
||||
const { page = 0, type = 'hot', userId, latitude, longitude } = event
|
||||
|
||||
try {
|
||||
let query = db.collection('posts')
|
||||
const skip = page * PAGE_SIZE
|
||||
|
||||
if (userId) {
|
||||
// 某用户的帖子
|
||||
query = query.where({ authorId: userId })
|
||||
} else if (type === 'feed') {
|
||||
// 关注的用户帖子
|
||||
const followsRes = await db.collection('follows')
|
||||
.where({ followerId: OPENID })
|
||||
.field({ followeeId: true })
|
||||
.get()
|
||||
const followeeIds = followsRes.data.map(f => f.followeeId)
|
||||
followeeIds.push(OPENID)
|
||||
query = query.where({ authorId: _.in(followeeIds) })
|
||||
} else if (type === 'nearby' && latitude && longitude) {
|
||||
// 附近帖子:使用地理围栏查询(简化版,用 geo_near)
|
||||
query = query.where(
|
||||
_.and([
|
||||
{ 'location.latitude': _.gt(latitude - 0.1) },
|
||||
{ 'location.latitude': _.lt(latitude + 0.1) },
|
||||
{ 'location.longitude': _.gt(longitude - 0.15) },
|
||||
{ 'location.longitude': _.lt(longitude + 0.15) },
|
||||
])
|
||||
)
|
||||
}
|
||||
// type === 'hot' 全量按热度排序
|
||||
|
||||
const total = await query.count()
|
||||
const postsRes = await query
|
||||
.orderBy('createdAt', 'desc')
|
||||
.skip(skip)
|
||||
.limit(PAGE_SIZE)
|
||||
.get()
|
||||
|
||||
const posts = postsRes.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: {
|
||||
list: enriched,
|
||||
total: total.total,
|
||||
hasMore: skip + posts.length < total.total,
|
||||
},
|
||||
}
|
||||
} catch (e) {
|
||||
return { code: -1, message: e.message }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user