110 lines
2.9 KiB
JavaScript
110 lines
2.9 KiB
JavaScript
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);
|
|
case 'count':
|
|
return await handleCount(userId);
|
|
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 } };
|
|
}
|
|
|
|
const MAX_LIST_PAGE_SIZE = 30;
|
|
|
|
async function handleList(userId, event) {
|
|
const { page = 1, pageSize = MAX_LIST_PAGE_SIZE } = event;
|
|
const limit = Math.min(Math.max(1, Number(pageSize) || 1), MAX_LIST_PAGE_SIZE);
|
|
const skip = (page - 1) * limit;
|
|
|
|
const collection = db.collection('download_logs');
|
|
|
|
const { data: logs } = await collection
|
|
.where({ userId })
|
|
.orderBy('createdAt', 'desc')
|
|
.skip(skip)
|
|
.limit(limit)
|
|
.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 };
|
|
}
|
|
|
|
async function handleCount(userId) {
|
|
const collection = db.collection('download_logs');
|
|
const res = await collection.where({ userId }).count();
|
|
return { code: 0, data: { count: res.total || 0 } };
|
|
}
|