41 lines
1.4 KiB
JavaScript
41 lines
1.4 KiB
JavaScript
const express = require("express");
|
|
const { connect, toId, serialize } = require("../db");
|
|
|
|
const router = express.Router();
|
|
|
|
router.get("/", async (req, res) => {
|
|
const db = await connect();
|
|
const absences = await db.collection("absences").find().sort({ startDate: 1 }).toArray();
|
|
res.json(absences.map(serialize));
|
|
});
|
|
|
|
router.post("/", async (req, res) => {
|
|
const { personId, startDate, endDate, note } = req.body;
|
|
if (!personId || !startDate || !endDate) {
|
|
return res
|
|
.status(400)
|
|
.json({ error: "personId, startDate und endDate sind erforderlich" });
|
|
}
|
|
const db = await connect();
|
|
const personObjectId = toId(personId);
|
|
if (!personObjectId || !(await db.collection("people").findOne({ _id: personObjectId }))) {
|
|
return res.status(400).json({ error: "Unbekannte Person" });
|
|
}
|
|
const doc = { personId, startDate, endDate, note: note || "" };
|
|
const result = await db.collection("absences").insertOne(doc);
|
|
res.status(201).json(serialize({ _id: result.insertedId, ...doc }));
|
|
});
|
|
|
|
router.delete("/:id", async (req, res) => {
|
|
const _id = toId(req.params.id);
|
|
if (!_id) return res.status(404).json({ error: "Abwesenheit nicht gefunden" });
|
|
const db = await connect();
|
|
const result = await db.collection("absences").deleteOne({ _id });
|
|
if (result.deletedCount === 0) {
|
|
return res.status(404).json({ error: "Abwesenheit nicht gefunden" });
|
|
}
|
|
res.status(204).end();
|
|
});
|
|
|
|
module.exports = router;
|