I'm building an API in express after some time away from it. This app helps users track their guitar routines. Here is an example of a DELETE function in my controller and the possible exceptions that can be thrown:
deleteOneRoutine = async (userId, routineId) => {
// If the given routineId is found in the DB
// AND the userId matches, delete it from DB
const selectedRoutine = await Routine.findOne({_id: routineId});
if (!selectedRoutine) {return 400};
if (selectedRoutine.userId != userId) {return 401};
const deleted = await selectedRoutine.remove();
if (!deleted) {return 500};
return deleted;
}
And here is the route that receives those error codes:
routineRouter.delete('/:routineId', async (req, res) => {
const userId = req.params.userId;
const routineId = req.params.routineId;
const deleted = await routineController.deleteOneRoutine(userId, routineId);
if (deleted === 400) {res.status(400).send('Requested routine could not be found.')}
else if (deleted === 401) {res.status(401).send('Unauthorized user.')}
else if (deleted === 500) {res.status(500).send('Server error. Could not delete routine.')}
else {res.status(200).send(`Successfully deleted routine with ID ${routineId}`)}
});
I'm wondering if there is a better way to handle this instead of manually passing back the error codes from the controller. Any help would be appreciated!