Enhanced delete functionality for filaments by adding a route handler that checks for dependencies before deletion. Updated the database service to support this check, ensuring objects in use cannot be deleted. Refactored related routes for consistency.
Some checks failed
farmcontrol/farmcontrol-api/pipeline/head There was a failure building this commit

This commit is contained in:
Tom Butcher 2026-03-08 01:53:07 +00:00
parent 6645898471
commit 0300e00c8f
3 changed files with 47 additions and 2 deletions

View File

@ -933,9 +933,28 @@ export const newObject = async ({ model, newData, user = null }, distributeChang
};
// Reusable function to delete an object by ID, with audit logging and distribution
export const deleteObject = async ({ model, id, user = null }, distributeChanges = true) => {
export const deleteObject = async (
{ model, id, user = null, checkUnused = false },
distributeChanges = true
) => {
try {
const parentType = model.modelName ? model.modelName : 'unknown';
if (checkUnused) {
const dependencies = await listObjectDependencies({ model, id });
if (dependencies?.error) {
return { error: dependencies.error, code: dependencies.code || 500 };
}
if (dependencies?.length > 0) {
return {
error: 'Object is in use and cannot be deleted',
code: 409,
dependencies: dependencies.length,
dependencyDetails: dependencies,
};
}
}
// Delete the object
const result = await model.findByIdAndDelete(id);

View File

@ -10,6 +10,7 @@ import {
editFilamentRouteHandler,
editMultipleFilamentsRouteHandler,
newFilamentRouteHandler,
deleteFilamentRouteHandler,
getFilamentStatsRouteHandler,
getFilamentHistoryRouteHandler,
} from '../../services/management/filaments.js';
@ -70,9 +71,13 @@ router.put('/', isAuthenticated, async (req, res) => {
editMultipleFilamentsRouteHandler(req, res);
});
// update printer info
// update filament info
router.put('/:id', isAuthenticated, async (req, res) => {
editFilamentRouteHandler(req, res);
});
router.delete('/:id', isAuthenticated, async (req, res) => {
deleteFilamentRouteHandler(req, res);
});
export default router;

View File

@ -9,6 +9,7 @@ import {
editObject,
editObjects,
newObject,
deleteObject,
getModelStats,
getModelHistory,
} from '../../database/database.js';
@ -194,6 +195,26 @@ export const newFilamentRouteHandler = async (req, res) => {
res.send(result);
};
export const deleteFilamentRouteHandler = async (req, res) => {
const id = new mongoose.Types.ObjectId(req.params.id);
logger.trace(`Filament with ID: ${id}`);
const result = await deleteObject({
model: filamentModel,
id,
user: req.user,
checkUnused: true,
});
if (result.error) {
logger.error('No filament deleted:', result.error);
return res.status(result.code).send(result);
}
logger.debug(`Deleted filament with ID: ${id}`);
res.send(result);
};
export const getFilamentStatsRouteHandler = async (req, res) => {
const result = await getModelStats({ model: filamentModel });
if (result?.error) {