From b514e81764f4e940344f6b38e8b3bc679acbec02 Mon Sep 17 00:00:00 2001 From: Spacelord Date: Tue, 16 May 2023 17:41:55 +0200 Subject: [PATCH] Added some error handling to categories api - AFLOW-13 - Added check if an category entry already exists. - Update prechek if all IDs are existing --- src/routes/api/v1/categories.ts | 45 +++++++++++++++++++++++++++------ 1 file changed, 37 insertions(+), 8 deletions(-) diff --git a/src/routes/api/v1/categories.ts b/src/routes/api/v1/categories.ts index 6e11beb..2fb187a 100644 --- a/src/routes/api/v1/categories.ts +++ b/src/routes/api/v1/categories.ts @@ -48,20 +48,43 @@ function post(req: Request, res: Response) { res.status(201).json({ status: 'created' }); }) .catch((err) => { - // TODO Catch if is a duplicate error and show a message to the user - log.db.error(err); - res.status(500).render(__path + '/src/frontend/errors/dbError.eta.html', { error: err }); + // 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); + res.status(500).render(__path + '/src/frontend/errors/dbError.eta.html', { error: err }); + } }); } // Update category. -function patch(req: Request, res: Response) { +async function patch(req: Request, res: Response) { // Check if required fields are present. if (!req.body.id || !req.body.name) { res.status(400).render(__path + '/src/frontend/errors/400.eta.html'); 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 .update({ where: { @@ -76,9 +99,15 @@ function patch(req: Request, res: Response) { res.status(201).json({ status: 'updated' }); }) .catch((err) => { - // TODO Catch if is a duplicate error and show a message to the user - log.db.error(err); - res.status(500).render(__path + '/src/frontend/errors/dbError.eta.html', { error: err }); + // 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); + 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(() => { - res.status(201).json({ status: 'deleted' }); + res.status(200).json({ status: 'deleted' }); }) .catch((err) => { log.db.error(err);