import express from 'express' import { requireAuth, requireAdmin } from './user.js' import Stability from '../model/stability.js' const router = express.Router() // 列出所有稳定性实验 router.get('/', requireAuth, async (req, res) => { try { const stabilities = await Stability.find().populate(['checks.checker', 'creater']) res.json(stabilities) } catch (error) { res.status(500).json({ message: '服务器错误', error: error.message }) } }) // 列出未完成的稳定性实验 router.get('/unend', requireAuth, async (req, res) => { try { const statilities = await Stability.find({ ended: false }).populate(['checks.checker', 'creater']) res.json(statilities) } catch (error) { res.status(500).json({ message: '服务器错误', error: error.message }) } }) // 创建稳定性实验 router.post('/', requireAuth, async (req, res) => { if (!req.body.batch) { return res.status(400).json({ message: '缺少必要字段' }) } try { const stability = await Stability.create({ creater: req.user.id, ...req.body, }) if (stability) { res.json(stability) } else { res.status(400).json({ message: '资源创建失败' }) } } catch (error) { res.status(500).json({ message: '服务器错误', error: error.message }) } }) // 删除稳定性实验 router.delete('/:id', requireAuth, requireAdmin, async (req, res) => { try { const stability = await Stability.findByIdAndDelete(req.params.id) if (stability) { res.json({ message: '删除成功' }) } else { res.status(404).json({ message: '删除失败' }) } } catch (error) { res.status(500).json({ message: '服务器错误', error: error.message }) } }) // 对 指定的稳定性实验进行check // id:稳定性实验id // checkid:检查点id router.post('/check/:id/:checkid', requireAuth, async (req, res) => { try { const stability = await Stability.findById(req.params.id) if (!stability) { return res.status(404).json({ message: `未找到id为${req.params.id}的记录` }) } stability.checks.forEach((check) => { if (check._id == req.params.checkid) { check.checked = true check.checker = req.user.id } }) stability.ended = stability.checks.every((check) => check.checked) await stability.save() res.json(stability) } catch (error) { res.status(500).json({ message: '服务器错误', error: error.message }) } }) // 更新稳定性实验 router.patch('/:id', requireAuth, async (req, res) => { try { const stability = await Stability.findByIdAndUpdate(req.params.id, req.body, { returnDocument: 'after' }) if (stability) { res.json(stability) } else { res.status(404).json({ message: `未找到id为${req.params.id}的记录` }) } } catch (error) { res.status(500).json({ message: '服务器错误', error: error.message }) } }) export { router as stabilityRouter }