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 } } }