93 lines
2.4 KiB
JavaScript
93 lines
2.4 KiB
JavaScript
const express = require('express');
|
|
const { db } = require('../database');
|
|
|
|
const router = express.Router();
|
|
|
|
router.get('/', (req, res) => {
|
|
const userId = req.user.userId;
|
|
|
|
db.all(
|
|
'SELECT date, status FROM calendar_marks WHERE user_id = ?',
|
|
[userId],
|
|
(err, rows) => {
|
|
if (err) {
|
|
return res.status(500).json({ success: false, error: '获取数据失败' });
|
|
}
|
|
|
|
const markedDates = {};
|
|
rows.forEach((row) => {
|
|
markedDates[row.date] = row.status;
|
|
});
|
|
|
|
res.json({ success: true, markedDates });
|
|
}
|
|
);
|
|
});
|
|
|
|
router.post('/', (req, res) => {
|
|
const userId = req.user.userId;
|
|
const { markedDates } = req.body || {};
|
|
|
|
if (!markedDates || typeof markedDates !== 'object') {
|
|
return res.status(400).json({ success: false, error: '无效的数据格式' });
|
|
}
|
|
|
|
const dbOperations = Object.entries(markedDates).map(([date, status]) => {
|
|
return new Promise((resolve, reject) => {
|
|
db.run(
|
|
`INSERT INTO calendar_marks (user_id, date, status, updated_at)
|
|
VALUES (?, ?, ?, CURRENT_TIMESTAMP)
|
|
ON CONFLICT(user_id, date) DO UPDATE SET
|
|
status = excluded.status,
|
|
updated_at = CURRENT_TIMESTAMP`,
|
|
[userId, date, status],
|
|
(err) => {
|
|
if (err) reject(err);
|
|
else resolve();
|
|
}
|
|
);
|
|
});
|
|
});
|
|
|
|
const dates = Object.keys(markedDates);
|
|
if (dates.length > 0) {
|
|
const placeholders = dates.map(() => '?').join(',');
|
|
dbOperations.push(
|
|
new Promise((resolve, reject) => {
|
|
db.run(
|
|
`DELETE FROM calendar_marks WHERE user_id = ? AND date NOT IN (${placeholders})`,
|
|
[userId, ...dates],
|
|
(err) => {
|
|
if (err) reject(err);
|
|
else resolve();
|
|
}
|
|
);
|
|
})
|
|
);
|
|
} else {
|
|
dbOperations.push(
|
|
new Promise((resolve, reject) => {
|
|
db.run(
|
|
'DELETE FROM calendar_marks WHERE user_id = ?',
|
|
[userId],
|
|
(err) => {
|
|
if (err) reject(err);
|
|
else resolve();
|
|
}
|
|
);
|
|
})
|
|
);
|
|
}
|
|
|
|
Promise.all(dbOperations)
|
|
.then(() => {
|
|
res.json({ success: true, message: '数据保存成功' });
|
|
})
|
|
.catch((err) => {
|
|
console.error('保存数据失败:', err);
|
|
res.status(500).json({ success: false, error: '保存数据失败' });
|
|
});
|
|
});
|
|
|
|
module.exports = router;
|