const db = uniCloud.database(); const _ = db.command; const uniID = require('uni-id-common'); module.exports = { _before: function () { // 通用预处理器 this.uniID = uniID.createInstance({ context: this.getClientInfo() }); }, /** * 浏览历史列表 * 只允许查询自己的记录。原实现接收 user_id 却完全不用, * 直接返回全表,任何登录用户都能拿到所有人的浏览记录。 */ async getHistoryList(query) { try { const payload = await this.uniID.checkToken(this.getUniIdToken()); if (payload.errCode) throw new Error('登录状态失效,请重新登录'); const requested = query && query.user_id; const user_id = requested || payload.uid; if (user_id !== payload.uid && !(payload.role || []).includes('admin')) { return { code: 403, msg: '无权查看他人浏览记录' }; } const res = await db.collection("cms-articles-log") .where({ user_id }) .orderBy('last_view_time', 'desc') .limit(100) .get(); return { code: 200, data: res.data }; } catch (e) { return { code: 500, msg: e.message }; } }, /** * 浏览历史条数,同样限定为本人 */ async getHistory(user_id) { try { const payload = await this.uniID.checkToken(this.getUniIdToken()); if (payload.errCode) throw new Error('登录状态失效,请重新登录'); const target = user_id || payload.uid; if (target !== payload.uid && !(payload.role || []).includes('admin')) { return { code: 403, msg: '无权查看他人浏览记录' }; } const count = await db.collection("cms-articles-log").where({ user_id: target }).count(); return { code: 200, total: count.total }; } catch (e) { return { code: 500, msg: e.message }; } } }