修改bug

This commit is contained in:
2026-06-18 15:38:28 +08:00
parent 0e43ccec72
commit 702b578e1e
57 changed files with 1378 additions and 66 deletions

View File

@@ -0,0 +1,91 @@
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()
const _ = db.command
const COMMENTS_COLLECTION = 'comments'
function isCollectionMissing(error) {
const text = String(error?.errMsg || error?.message || error || '')
return (
text.includes('collection not exist') ||
text.includes('collection not exists') ||
text.includes('collection is not exists') ||
text.includes('DATABASE_COLLECTION_NOT_EXIST') ||
text.includes('-502005')
)
}
function isCollectionAlreadyExists(error) {
const text = String(error?.errMsg || error?.message || error || '')
return text.includes('collection already exists') || text.includes('DATABASE_COLLECTION_ALREADY_EXIST')
}
async function ensureCommentsCollection() {
if (typeof db.createCollection !== 'function') {
throw new Error('comments collection does not exist')
}
try {
await db.createCollection(COMMENTS_COLLECTION)
} catch (error) {
if (!isCollectionAlreadyExists(error)) throw error
}
}
async function addComment(data) {
try {
return await db.collection(COMMENTS_COLLECTION).add({ data })
} catch (error) {
if (!isCollectionMissing(error)) throw error
await ensureCommentsCollection()
return db.collection(COMMENTS_COLLECTION).add({ data })
}
}
exports.main = async event => {
const { OPENID } = cloud.getWXContext()
if (!OPENID) throw new Error('no openid in wx context')
const postId = String(event.postId || '').trim()
const content = String(event.content || '').trim()
if (!postId) throw new Error('postId is required')
if (!content) throw new Error('content is required')
const [postRes, userRes] = await Promise.all([
db.collection('posts').doc(postId).get(),
db.collection('users').where({ openid: OPENID }).limit(1).get()
])
if (!postRes.data) throw new Error('post not found')
if (!userRes.data.length) throw new Error('user not found')
const now = Date.now()
const user = userRes.data[0]
const result = await addComment({
postId,
openid: OPENID,
authorId: user._id,
authorSnapshot: {
name: user.nickname || '',
avatarKey: user.avatarKey || 'gradient-avatar-1',
avatarUrl: user.avatarUrl || ''
},
content: content.slice(0, 500),
createdAt: now,
updatedAt: now
})
await db.collection('posts').doc(postId).update({
data: {
'counts.comments': _.inc(1),
updatedAt: now
}
})
const updatedPost = await db.collection('posts').doc(postId).get()
return {
commentId: result._id,
comments: updatedPost.data.counts?.comments || 0
}
}

View File

@@ -0,0 +1,8 @@
{
"name": "commentCreate",
"version": "1.0.0",
"main": "index.js",
"dependencies": {
"wx-server-sdk": "latest"
}
}

View File

@@ -2,11 +2,31 @@ const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()
const DRAFTS_COLLECTION = 'drafts'
function isCollectionMissing(error) {
const text = String(error?.errMsg || error?.message || error || '')
return (
text.includes('collection not exist') ||
text.includes('collection not exists') ||
text.includes('collection is not exists') ||
text.includes('DATABASE_COLLECTION_NOT_EXIST') ||
text.includes('-502005')
)
}
exports.main = async () => {
const { OPENID } = cloud.getWXContext()
if (!OPENID) throw new Error('no openid in wx context')
const res = await db.collection('drafts').where({ openid: OPENID }).limit(1).get()
let res
try {
res = await db.collection(DRAFTS_COLLECTION).where({ openid: OPENID }).limit(1).get()
} catch (error) {
if (isCollectionMissing(error)) return { draft: null }
throw error
}
if (!res.data.length) return { draft: null }
const record = res.data[0]
return { draft: record.draft || null, updatedAt: record.updatedAt }

View File

@@ -2,23 +2,64 @@ const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()
const DRAFTS_COLLECTION = 'drafts'
function isCollectionMissing(error) {
const text = String(error?.errMsg || error?.message || error || '')
return (
text.includes('collection not exist') ||
text.includes('collection not exists') ||
text.includes('collection is not exists') ||
text.includes('DATABASE_COLLECTION_NOT_EXIST') ||
text.includes('-502005')
)
}
function isCollectionAlreadyExists(error) {
const text = String(error?.errMsg || error?.message || error || '')
return text.includes('collection already exists') || text.includes('DATABASE_COLLECTION_ALREADY_EXIST')
}
async function ensureDraftsCollection() {
if (typeof db.createCollection !== 'function') {
throw new Error('drafts collection does not exist')
}
try {
await db.createCollection(DRAFTS_COLLECTION)
} catch (error) {
if (!isCollectionAlreadyExists(error)) throw error
}
}
async function getExistingDraft(openid) {
try {
return await db.collection(DRAFTS_COLLECTION).where({ openid }).limit(1).get()
} catch (error) {
if (!isCollectionMissing(error)) throw error
await ensureDraftsCollection()
return { data: [] }
}
}
exports.main = async event => {
const { OPENID } = cloud.getWXContext()
if (!OPENID) throw new Error('no openid in wx context')
const now = Date.now()
const data = {
openid: OPENID,
draft: event.draft || {},
updatedAt: now
}
const existed = await db.collection('drafts').where({ openid: OPENID }).limit(1).get()
const existed = await getExistingDraft(OPENID)
const collection = db.collection(DRAFTS_COLLECTION)
if (existed.data.length) {
await db.collection('drafts').doc(existed.data[0]._id).update({ data })
await collection.doc(existed.data[0]._id).update({ data })
return { draftId: existed.data[0]._id, updatedAt: now }
}
const result = await db.collection('drafts').add({ data })
const result = await collection.add({ data })
return { draftId: result._id, updatedAt: now }
}

View File

@@ -74,12 +74,25 @@ exports.main = async event => {
favSet = new Set(favRes.data.map(f => f.postId))
}
const list = res.data.map(post => ({
// Resolve authors' current profile (real avatar image) so feed avatars load
// and stay fresh, even for posts whose snapshot predates avatar upload.
const authorIds = [...new Set(res.data.map(p => p.authorId).filter(Boolean))]
const authorMap = new Map()
for (let i = 0; i < authorIds.length; i += 100) {
const chunk = authorIds.slice(i, i + 100)
const usersRes = await safeGet('users', { _id: _.in(chunk) }, 100)
usersRes.data.forEach(u => authorMap.set(u._id, u))
}
const list = res.data.map(post => {
const author = authorMap.get(post.authorId)
return {
_id: post._id,
author: {
id: post.authorId || '',
name: post.authorSnapshot?.name || '用户',
avatarKey: post.authorSnapshot?.avatarKey || 'gradient-avatar-1'
name: (author && author.nickname) || post.authorSnapshot?.name || '用户',
avatarKey: (author && author.avatarKey) || post.authorSnapshot?.avatarKey || 'gradient-avatar-1',
avatarUrl: (author && author.avatarUrl) || post.authorSnapshot?.avatarUrl || ''
},
pet: post.petSnapshot || { name: '', breed: '' },
body: post.content || '',
@@ -98,7 +111,8 @@ exports.main = async event => {
},
likedByMe: likedSet.has(post._id),
favoritedByMe: favSet.has(post._id)
}))
}
})
const last = res.data[res.data.length - 1]
return { list, nextCursor: last ? String(last.createdAt) : '' }

View File

@@ -2,6 +2,18 @@ const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()
const _ = db.command
async function fetchUsers(ids) {
if (!ids.length) return []
const out = []
for (let i = 0; i < ids.length; i += 100) {
const chunk = ids.slice(i, i + 100)
const res = await db.collection('users').where({ _id: _.in(chunk) }).limit(100).get()
out.push(...res.data)
}
return out
}
function hashId(id) {
let h = 5381
@@ -46,19 +58,48 @@ function distanceText(petLoc, userLoc) {
}
exports.main = async event => {
const { OPENID } = cloud.getWXContext()
const filter = event.filters?.type || 'all'
const userLoc = event.location || null
const query = {}
if (filter === 'dog' || filter === 'cat') query.species = filter
if (filter === 'online') query.online = true
let meId = ''
let followingSet = new Set()
let followerSet = new Set()
if (OPENID) {
const meRes = await db.collection('users').where({ openid: OPENID }).limit(1).get()
const me = meRes.data[0]
if (me) {
meId = me._id
const [followingRes, followerRes] = await Promise.all([
db.collection('follows').where({ followerId: meId }).limit(500).get(),
db.collection('follows').where({ followeeId: meId }).limit(500).get()
])
followingSet = new Set(followingRes.data.map(f => f.followeeId))
followerSet = new Set(followerRes.data.map(f => f.followerId))
}
}
const res = await db.collection('pets').where(query).limit(50).get()
const ownerIds = [...new Set(res.data.map(pet => pet.ownerId).filter(Boolean))]
const owners = await fetchUsers(ownerIds)
const ownerMap = new Map(owners.map(owner => [owner._id, owner]))
const list = res.data.map(pet => {
const realCoord = pet.location && typeof pet.location.latitude === 'number' ? pet.location : null
const coord = realCoord || (userLoc ? syntheticCoord(pet._id, userLoc) : null)
const owner = ownerMap.get(pet.ownerId)
const isFollowing = followingSet.has(pet.ownerId)
const isFollowedBy = followerSet.has(pet.ownerId)
return {
...pet,
ownerName: owner?.nickname || '',
isMine: Boolean(meId && pet.ownerId === meId),
isFollowing,
isFriend: isFollowing && isFollowedBy,
latitude: coord ? coord.latitude : undefined,
longitude: coord ? coord.longitude : undefined,
distanceText: distanceText(coord, userLoc) || pet.distanceText || null,

View File

@@ -0,0 +1,112 @@
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()
const _ = db.command
// Query a collection that may not exist yet (created lazily on first write).
async function safeGet(collection, where, limit = 200, orderBy) {
try {
let query = db.collection(collection).where(where)
if (orderBy) query = query.orderBy(orderBy.field, orderBy.direction)
return await query.limit(limit).get()
} catch (e) {
return { data: [] }
}
}
function formatTimeText(ts) {
const diff = Date.now() - ts
const mins = Math.floor(diff / 60000)
if (mins < 1) return '刚刚'
if (mins < 60) return `${mins} 分钟前`
const hours = Math.floor(mins / 60)
if (hours < 24) return `${hours} 小时前`
const days = Math.floor(hours / 24)
if (days === 1) return '昨天'
if (days < 7) return `${days} 天前`
const d = new Date(ts)
return `${d.getMonth() + 1}${d.getDate()}`
}
exports.main = async event => {
const { OPENID } = cloud.getWXContext()
const postId = String(event.postId || '').trim()
if (!postId) throw new Error('postId is required')
const postRes = await db.collection('posts').doc(postId).get().catch(() => null)
if (!postRes || !postRes.data) return { post: null, comments: [] }
const post = postRes.data
// Resolve the author's current profile (fresh avatar), liked/favorited state.
let author = null
if (post.authorId) {
const authorRes = await safeGet('users', { _id: post.authorId }, 1)
author = authorRes.data[0] || null
}
let likedByMe = false
let favoritedByMe = false
if (OPENID) {
const [likedRes, favRes] = await Promise.all([
safeGet('postLikes', { openid: OPENID, postId }, 1),
safeGet('postFavorites', { openid: OPENID, postId }, 1)
])
likedByMe = likedRes.data.length > 0
favoritedByMe = favRes.data.length > 0
}
const mappedPost = {
_id: post._id,
author: {
id: post.authorId || '',
name: (author && author.nickname) || post.authorSnapshot?.name || '用户',
avatarKey: (author && author.avatarKey) || post.authorSnapshot?.avatarKey || 'gradient-avatar-1',
avatarUrl: (author && author.avatarUrl) || post.authorSnapshot?.avatarUrl || ''
},
pet: post.petSnapshot || { name: '', breed: '' },
body: post.content || '',
topics: post.topics || [],
media: Array.isArray(post.media)
? post.media.map(m => (typeof m === 'string' ? m : m && (m.url || m.fileId))).filter(Boolean)
: [],
mediaTone: post.mediaTone || 'pet-1',
sticker: post.sticker || undefined,
locationText: post.locationText || '',
timeText: formatTimeText(post.createdAt || Date.now()),
counts: {
likes: post.counts?.likes || 0,
comments: post.counts?.comments || 0,
favorites: post.counts?.favorites || 0
},
likedByMe,
favoritedByMe
}
// Comments, oldest first. Resolve each author's current profile for avatars.
const commentsRes = await safeGet('comments', { postId }, 200, { field: 'createdAt', direction: 'asc' })
const commentAuthorIds = [...new Set(commentsRes.data.map(c => c.authorId).filter(Boolean))]
const authorMap = new Map()
for (let i = 0; i < commentAuthorIds.length; i += 100) {
const chunk = commentAuthorIds.slice(i, i + 100)
const usersRes = await safeGet('users', { _id: _.in(chunk) }, 100)
usersRes.data.forEach(u => authorMap.set(u._id, u))
}
const comments = commentsRes.data.map(c => {
const u = authorMap.get(c.authorId)
return {
_id: c._id,
author: {
id: c.authorId || '',
name: (u && u.nickname) || c.authorSnapshot?.name || '用户',
avatarKey: (u && u.avatarKey) || c.authorSnapshot?.avatarKey || 'gradient-avatar-1',
avatarUrl: (u && u.avatarUrl) || c.authorSnapshot?.avatarUrl || ''
},
content: c.content || '',
timeText: formatTimeText(c.createdAt || Date.now())
}
})
return { post: mappedPost, comments }
}

View File

@@ -0,0 +1,8 @@
{
"name": "postDetail",
"version": "1.0.0",
"main": "index.js",
"dependencies": {
"wx-server-sdk": "latest"
}
}

View File

@@ -3,22 +3,63 @@ const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()
const _ = db.command
const POST_LIKES_COLLECTION = 'postLikes'
function isCollectionMissing(error) {
const text = String(error?.errMsg || error?.message || error || '')
return (
text.includes('collection not exist') ||
text.includes('collection not exists') ||
text.includes('collection is not exists') ||
text.includes('DATABASE_COLLECTION_NOT_EXIST') ||
text.includes('-502005')
)
}
function isCollectionAlreadyExists(error) {
const text = String(error?.errMsg || error?.message || error || '')
return text.includes('collection already exists') || text.includes('DATABASE_COLLECTION_ALREADY_EXIST')
}
async function ensurePostLikesCollection() {
if (typeof db.createCollection !== 'function') {
throw new Error('postLikes collection does not exist')
}
try {
await db.createCollection(POST_LIKES_COLLECTION)
} catch (error) {
if (!isCollectionAlreadyExists(error)) throw error
}
}
async function getExistingLike(postId, openid) {
try {
return await db.collection(POST_LIKES_COLLECTION).where({ postId, openid }).limit(1).get()
} catch (error) {
if (!isCollectionMissing(error)) throw error
await ensurePostLikesCollection()
return { data: [] }
}
}
exports.main = async event => {
const { OPENID } = cloud.getWXContext()
const { postId, liked } = event
if (!OPENID) throw new Error('no openid in wx context')
if (!postId) throw new Error('postId is required')
const existed = await db.collection('postLikes').where({ postId, openid: OPENID }).limit(1).get()
const existed = await getExistingLike(postId, OPENID)
const collection = db.collection(POST_LIKES_COLLECTION)
let delta = 0
if (liked && !existed.data.length) {
await db.collection('postLikes').add({ data: { postId, openid: OPENID, createdAt: Date.now() } })
await collection.add({ data: { postId, openid: OPENID, createdAt: Date.now() } })
delta = 1
}
if (!liked && existed.data.length) {
await db.collection('postLikes').doc(existed.data[0]._id).remove()
await collection.doc(existed.data[0]._id).remove()
delta = -1
}
@@ -29,4 +70,3 @@ exports.main = async event => {
const post = await db.collection('posts').doc(postId).get()
return { liked: Boolean(liked), likes: post.data.counts?.likes || 0 }
}

View File

@@ -0,0 +1,90 @@
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()
const _ = db.command
async function safeGet(collection, where, limit = 200) {
try {
return await db.collection(collection).where(where).limit(limit).get()
} catch (e) {
return { data: [] }
}
}
function formatTimeText(ts) {
const diff = Date.now() - ts
const mins = Math.floor(diff / 60000)
if (mins < 1) return '刚刚'
if (mins < 60) return `${mins} 分钟前`
const hours = Math.floor(mins / 60)
if (hours < 24) return `${hours} 小时前`
const days = Math.floor(hours / 24)
if (days === 1) return '昨天'
if (days < 7) return `${days} 天前`
const d = new Date(ts)
return `${d.getMonth() + 1}${d.getDate()}`
}
// List a user's own posts. Defaults to the caller; pass authorId to view
// another user (only public posts are returned for others).
exports.main = async event => {
const { OPENID } = cloud.getWXContext()
if (!OPENID) throw new Error('no openid in wx context')
let authorOpenid = OPENID
let viewingSelf = true
if (event.authorId) {
const u = await db.collection('users').doc(event.authorId).get().catch(() => null)
if (!u || !u.data) return { list: [] }
authorOpenid = u.data.openid
viewingSelf = authorOpenid === OPENID
}
const where = { authorOpenid }
if (!viewingSelf) where.visibility = 'public'
const res = await db.collection('posts')
.where(where)
.orderBy('createdAt', 'desc')
.limit(50)
.get()
if (!res.data.length) return { list: [] }
const postIds = res.data.map(p => p._id)
const [likedRes, favRes] = await Promise.all([
safeGet('postLikes', { openid: OPENID, postId: _.in(postIds) }),
safeGet('postFavorites', { openid: OPENID, postId: _.in(postIds) })
])
const likedSet = new Set(likedRes.data.map(l => l.postId))
const favSet = new Set(favRes.data.map(f => f.postId))
const list = res.data.map(post => ({
_id: post._id,
author: {
id: post.authorId || '',
name: post.authorSnapshot?.name || '用户',
avatarKey: post.authorSnapshot?.avatarKey || 'gradient-avatar-1'
},
pet: post.petSnapshot || { name: '', breed: '' },
body: post.content || '',
topics: post.topics || [],
media: Array.isArray(post.media)
? post.media.map(m => (typeof m === 'string' ? m : m && (m.url || m.fileId))).filter(Boolean)
: [],
mediaTone: post.mediaTone || 'pet-1',
sticker: post.sticker || undefined,
locationText: post.locationText || '',
timeText: formatTimeText(post.createdAt || Date.now()),
counts: {
likes: post.counts?.likes || 0,
comments: post.counts?.comments || 0,
favorites: post.counts?.favorites || 0
},
likedByMe: likedSet.has(post._id),
favoritedByMe: favSet.has(post._id)
}))
return { list }
}

View File

@@ -0,0 +1,8 @@
{
"name": "userPosts",
"version": "1.0.0",
"main": "index.js",
"dependencies": {
"wx-server-sdk": "latest"
}
}