feat: 开发收藏和下载功能

This commit is contained in:
R524809
2026-05-06 18:32:15 +08:00
parent 9bdf850f20
commit c0b1bfddb0
17 changed files with 1262 additions and 127 deletions
+98
View File
@@ -0,0 +1,98 @@
const cloud = require('wx-server-sdk');
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database();
const command = db.command;
exports.main = async (event) => {
const wxContext = cloud.getWXContext();
const openid = wxContext.OPENID;
// 获取 userId
const { data: users } = await db
.collection('users')
.where({ openid })
.limit(1)
.get();
if (users.length === 0) {
return { code: -1, message: '用户未登录' };
}
const userId = users[0]._id;
const { action } = event;
switch (action) {
case 'add':
return await handleAdd(userId, event);
case 'list':
return await handleList(userId, event);
default:
return { code: -1, message: '未知操作' };
}
};
async function handleAdd(userId, event) {
const { worksheetId } = event;
if (!worksheetId) return { code: -1, message: 'worksheetId 不能为空' };
const collection = db.collection('download_logs');
const record = {
userId,
worksheetId,
createdAt: db.serverDate(),
};
const { _id } = await collection.add({ data: record });
// worksheets.downloads +1
try {
await db.collection('worksheets').doc(worksheetId).update({
data: {
downloads: command.inc(1),
updatedAt: db.serverDate(),
},
});
} catch (e) {
console.warn('更新 worksheets.downloads 失败', e);
}
return { code: 0, data: { _id, ...record } };
}
async function handleList(userId, event) {
const { page = 1, pageSize = 20 } = event;
const skip = (page - 1) * pageSize;
const collection = db.collection('download_logs');
const { data: logs } = await collection
.where({ userId })
.orderBy('createdAt', 'desc')
.skip(skip)
.limit(pageSize)
.get();
if (logs.length === 0) {
return { code: 0, data: [] };
}
// 关联查询 worksheets 信息
const worksheetIds = [...new Set(logs.map((l) => l.worksheetId))];
const { data: worksheets } = await db
.collection('worksheets')
.where({ _id: command.in(worksheetIds) })
.get();
const worksheetMap = {};
worksheets.forEach((w) => {
worksheetMap[w._id] = w;
});
const result = logs.map((l) => ({
...l,
worksheet: worksheetMap[l.worksheetId] || null,
}));
return { code: 0, data: result };
}
@@ -0,0 +1,8 @@
{
"name": "user-download-logs",
"version": "1.0.0",
"main": "index.js",
"dependencies": {
"wx-server-sdk": "^3.0.4"
}
}