Refactor position move logic
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
const isMissingPositionColumn = (error) =>
|
||||
error &&
|
||||
error.code === "ER_BAD_FIELD_ERROR" &&
|
||||
String(error.sqlMessage || "").includes("position");
|
||||
|
||||
const moveByPosition = async ({
|
||||
db,
|
||||
table,
|
||||
id,
|
||||
direction,
|
||||
selectQuery,
|
||||
missingColumnMessage,
|
||||
notFoundMessage,
|
||||
}) => {
|
||||
if (direction !== "up" && direction !== "down") {
|
||||
return { status: 400, body: { error: "Ungueltige Richtung" } };
|
||||
}
|
||||
|
||||
let rows;
|
||||
|
||||
try {
|
||||
await db.query(
|
||||
`UPDATE ${table} SET position = id WHERE position IS NULL`
|
||||
);
|
||||
|
||||
;[rows] = await db.query(selectQuery);
|
||||
} catch (error) {
|
||||
if (isMissingPositionColumn(error)) {
|
||||
return { status: 400, body: { error: missingColumnMessage } };
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
const index = rows.findIndex((row) => row.id == id);
|
||||
|
||||
if (index === -1) {
|
||||
return { status: 404, body: { error: notFoundMessage } };
|
||||
}
|
||||
|
||||
const swapIndex = direction === "up" ? index - 1 : index + 1;
|
||||
|
||||
if (swapIndex < 0 || swapIndex >= rows.length) {
|
||||
return { status: 200, body: { 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 ${table} SET position = ? WHERE id = ?`,
|
||||
[i + 1, rows[i].id]
|
||||
);
|
||||
}
|
||||
|
||||
return { status: 200, body: { success: true } };
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
moveByPosition,
|
||||
isMissingPositionColumn,
|
||||
};
|
||||
Reference in New Issue
Block a user