initial
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
const express = require("express");
|
||||
const { connect, toId, serialize } = require("../db");
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.get("/", async (req, res) => {
|
||||
const db = await connect();
|
||||
const projects = await db.collection("projects").find().sort({ name: 1 }).toArray();
|
||||
res.json(projects.map(serialize));
|
||||
});
|
||||
|
||||
router.post("/", async (req, res) => {
|
||||
const { name, description, color } = req.body;
|
||||
if (!name || typeof name !== "string") {
|
||||
return res.status(400).json({ error: "name ist erforderlich" });
|
||||
}
|
||||
const db = await connect();
|
||||
const doc = {
|
||||
name,
|
||||
description: description || "",
|
||||
color: color || "#3E5C50"
|
||||
};
|
||||
const result = await db.collection("projects").insertOne(doc);
|
||||
res.status(201).json(serialize({ _id: result.insertedId, ...doc }));
|
||||
});
|
||||
|
||||
router.put("/:id", async (req, res) => {
|
||||
const _id = toId(req.params.id);
|
||||
if (!_id) return res.status(404).json({ error: "Projekt nicht gefunden" });
|
||||
|
||||
const { name, description, color } = req.body;
|
||||
const update = {};
|
||||
if (name !== undefined) update.name = name;
|
||||
if (description !== undefined) update.description = description;
|
||||
if (color !== undefined) update.color = color;
|
||||
|
||||
const db = await connect();
|
||||
const updated = await db
|
||||
.collection("projects")
|
||||
.findOneAndUpdate({ _id }, { $set: update }, { returnDocument: "after" });
|
||||
|
||||
if (!updated) return res.status(404).json({ error: "Projekt nicht gefunden" });
|
||||
res.json(serialize(updated));
|
||||
});
|
||||
|
||||
router.delete("/:id", async (req, res) => {
|
||||
const _id = toId(req.params.id);
|
||||
if (!_id) return res.status(404).json({ error: "Projekt nicht gefunden" });
|
||||
|
||||
const db = await connect();
|
||||
const result = await db.collection("projects").deleteOne({ _id });
|
||||
if (result.deletedCount === 0) {
|
||||
return res.status(404).json({ error: "Projekt nicht gefunden" });
|
||||
}
|
||||
await db.collection("tasks").deleteMany({ projectId: req.params.id });
|
||||
res.status(204).end();
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
Reference in New Issue
Block a user