Improve error handling and ordering flows

This commit is contained in:
ecki
2026-04-06 17:50:00 +02:00
parent 8aa85d47a7
commit fef108cf53
8 changed files with 488 additions and 110 deletions
+64
View File
@@ -1,12 +1,76 @@
const express = require("express");
const router = express.Router();
const db = require("../db");
const controller = require("../controllers/resourceController");
const isMissingPositionColumn = (error) =>
error && error.code === "ER_BAD_FIELD_ERROR" && String(error.sqlMessage || "").includes("position");
router.get("/active", controller.getActive);
router.get("/cancelled", controller.getCancelled);
router.post("/:id/move", async (req, res) => {
const { direction } = req.body
if (direction !== "up" && direction !== "down") {
return res.status(400).json({ error: "Ungueltige Richtung" })
}
try {
let rows
try {
await db.query(
"UPDATE resources SET position = id WHERE position IS NULL"
)
;[rows] = await db.query(
"SELECT id FROM resources WHERE status != 'gekündigt' ORDER BY position, id"
)
} catch (e) {
if (isMissingPositionColumn(e)) {
return res.status(400).json({ error: "Position-Spalte in resources fehlt noch" })
}
throw e
}
const index = rows.findIndex(r => r.id == req.params.id)
if (index === -1) {
return res.status(404).json({ error: "Ressource nicht gefunden" })
}
const swapIndex = direction === "up" ? index - 1 : index + 1
if (swapIndex < 0 || swapIndex >= rows.length) {
return res.json({ success: true })
}
const moved = rows.splice(index, 1)[0]
rows.splice(swapIndex, 0, moved)
for(let i = 0; i < rows.length; i++){
await db.query(
"UPDATE resources SET position=? WHERE id=?",
[i + 1, rows[i].id]
)
}
res.json({ success: true })
} catch (e) {
console.error("MOVE resource error:", e)
res.status(500).json({ error: "Reihenfolge konnte nicht geaendert werden" })
}
})
router.post("/", controller.create);
router.put("/:id", controller.update);
router.delete("/:id", controller.remove);
module.exports = router;