Files
t/uniCloud-alipay/cloudfunctions/uni-cms-articles/index.obj.js
T
2025-03-12 20:11:03 +08:00

64 lines
1.4 KiB
JavaScript

const db = uniCloud.database()
const collection = db.collection('uni-cms-articles')
module.exports = {
_before: function () { // 通用预处理器
},
async getTotal() {
try {
const res = await collection.count()
return {
code: 200,
message: 'success',
total: res.total
}
} catch (err) {
return {
code: 500,
message: err.message
}
}
},
// 文章访问日志服务
async detailLog(query) {
let datetime = new Date();
if (!query.userId) {
throw new Error('未登录用户无法记录访问日志');
}
try {
// 查询是否存在该用户对同一文章的访问记录
console.log(query.articleId);
const { data: existingLog } = await db.collection('cms-articles-log')
.where({
article_id: query.articleId
})
.get();
// 存在则更新,否则新增
if (existingLog.length > 0) {
await db.collection('cms-articles-log')
.doc(existingLog[0]._id)
.update({
last_view_time: datetime // 使用服务器时间
});
} else {
await db.collection('cms-articles-log')
.add({
user_id: query.userId,
article_id: query.articleId,
first_view_time: datetime,
last_view_time: datetime
});
}
return { code: 0, msg: '日志记录成功' };
} catch (err) {
console.error('日志记录失败:', err);
return { code: -1, msg: '系统异常,请重试' };
}
}
}