Refactor position move logic
This commit is contained in:
+12
-49
@@ -2,63 +2,26 @@ 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");
|
||||
const { moveByPosition } = require("../helpers/positionMove");
|
||||
|
||||
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 {
|
||||
const { direction } = req.body;
|
||||
|
||||
let rows
|
||||
const result = await moveByPosition({
|
||||
db,
|
||||
table: "resources",
|
||||
id: req.params.id,
|
||||
direction,
|
||||
selectQuery: "SELECT id FROM resources WHERE status != 'gekündigt' ORDER BY position, id",
|
||||
missingColumnMessage: "Position-Spalte in resources fehlt noch",
|
||||
notFoundMessage: "Ressource nicht gefunden",
|
||||
});
|
||||
|
||||
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 })
|
||||
res.status(result.status).json(result.body);
|
||||
|
||||
} catch (e) {
|
||||
console.error("MOVE resource error:", e)
|
||||
|
||||
Reference in New Issue
Block a user