chore: refactor all delete endpoints to use if/else instead of .catch() and .error()

This commit is contained in:
Agusti Fernandez Pardo committed 2022-03-27 01:08:00 +01:00
1 parent 936572e7e1
commit 396c5b8d8c
6 files changed
+53 -94

No files matched your search

+9 -16
View File
@@ -10,25 +10,18 @@ type ResponseData = {
error?: unknown;
};
export async function user(req: NextApiRequest, res: NextApiResponse<ResponseData>) {
export async function deleteUser(req: NextApiRequest, res: NextApiResponse<ResponseData>) {
const { query, method } = req;
const safe = await schemaQueryIdParseInt.safeParse(query);
if (method === "DELETE" && safe.success) {
// DELETE WILL DELETE THE EVENT TYPE
prisma.user
if (method === "DELETE" && safe.success && safe.data) {
const user = await prisma.user
.delete({ where: { id: safe.data.id } })
.then(() => {
// We only remove the user type from the database if there's an existing resource.
res.status(200).json({ message: `user-type with id: ${safe.data.id} deleted successfully` });
})
.catch((error) => {
// This catches the error thrown by prisma.user.delete() if the resource is not found.
res.status(400).json({ message: `Resource with id:${safe.data.id} was not found`, error: error });
});
} else {
// We only remove the user type from the database if there's an existing resource.
if (user) res.status(200).json({ message: `user with id: ${safe.data.id} deleted successfully` });
// This catches the error thrown by prisma.user.delete() if the resource is not found.
else res.status(400).json({ message: `Resource with id:${safe.data.id} was not found`});
// Reject any other HTTP method than POST
res.status(405).json({ message: "Only DELETE Method allowed in /user-types/[id]/delete endpoint" });
}
} else res.status(405).json({ message: "Only DELETE Method allowed" });
}
export default withValidQueryIdTransformParseInt(user);
export default withValidQueryIdTransformParseInt(deleteUser);