Added some error handling to categories api

- AFLOW-13
- Added check if an category entry already exists.
- Update prechek if all IDs are existing
This commit is contained in:
Leon Meier 2023-05-16 17:41:55 +02:00
parent e82d16af3e
commit b514e81764

View File

@ -48,20 +48,43 @@ function post(req: Request, res: Response) {
res.status(201).json({ status: 'created' }); res.status(201).json({ status: 'created' });
}) })
.catch((err) => { .catch((err) => {
// TODO Catch if is a duplicate error and show a message to the user // Check if an entry already exists.
if (err.code === 'P2002') {
// P2002 -> "Unique constraint failed on the {constraint}"
// https://www.prisma.io/docs/reference/api-reference/error-reference
res.status(409).json({ error: 'Category already exists.' });
} else {
log.db.error(err); log.db.error(err);
res.status(500).render(__path + '/src/frontend/errors/dbError.eta.html', { error: err }); res.status(500).render(__path + '/src/frontend/errors/dbError.eta.html', { error: err });
}
}); });
} }
// Update category. // Update category.
function patch(req: Request, res: Response) { async function patch(req: Request, res: Response) {
// Check if required fields are present. // Check if required fields are present.
if (!req.body.id || !req.body.name) { if (!req.body.id || !req.body.name) {
res.status(400).render(__path + '/src/frontend/errors/400.eta.html'); res.status(400).render(__path + '/src/frontend/errors/400.eta.html');
return; return;
} }
// Check if the category id exists. If not return 410 Gone.
try {
const result = await prisma.itemCategory.findUnique({
where: {
id: parseInt(req.body.id)
}
});
if (result === null) {
res.status(410).json({ error: 'category does not exist.' });
return;
}
} catch (err) {
log.db.error(err);
res.status(500).render(__path + '/src/frontend/errors/dbError.eta.html', { error: err });
}
prisma.itemCategory prisma.itemCategory
.update({ .update({
where: { where: {
@ -76,9 +99,15 @@ function patch(req: Request, res: Response) {
res.status(201).json({ status: 'updated' }); res.status(201).json({ status: 'updated' });
}) })
.catch((err) => { .catch((err) => {
// TODO Catch if is a duplicate error and show a message to the user // Check if an entry already exists.
if (err.code === 'P2002') {
// P2002 -> "Unique constraint failed on the {constraint}"
// https://www.prisma.io/docs/reference/api-reference/error-reference
res.status(409).json({ error: 'Category already exists.' });
} else {
log.db.error(err); log.db.error(err);
res.status(500).render(__path + '/src/frontend/errors/dbError.eta.html', { error: err }); res.status(500).render(__path + '/src/frontend/errors/dbError.eta.html', { error: err });
}
}); });
} }
@ -114,7 +143,7 @@ async function del(req: Request, res: Response) {
} }
}) })
.then(() => { .then(() => {
res.status(201).json({ status: 'deleted' }); res.status(200).json({ status: 'deleted' });
}) })
.catch((err) => { .catch((err) => {
log.db.error(err); log.db.error(err);