Skip to content

Commit

Permalink
Properly handle throwing a duplicate patient error
Browse files Browse the repository at this point in the history
  • Loading branch information
samau3 committed Sep 12, 2024
1 parent 30ffd56 commit 338c772
Showing 1 changed file with 38 additions and 26 deletions.
64 changes: 38 additions & 26 deletions server/routes/api/v1/patients/create.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { Role } from '../../../../models/user.js';
import { StatusCodes } from 'http-status-codes';



export default async function (fastify, _opts) {
fastify.post(
'/',
Expand Down Expand Up @@ -67,39 +69,49 @@ export default async function (fastify, _opts) {
const { id } = request.body;

const userId = request.user.id;

const newPatient = await fastify.prisma.$transaction(async (tx) => {
// Check if the patient already exists
const exists = await tx.patient.findUnique({
where: { id },
});
if (exists)
throw reply.status(StatusCodes.CONFLICT).send({
message: `Patient with ID ${id} already exists in database.`,
try {
const newPatient = await fastify.prisma.$transaction(async (tx) => {
// Check if the patient already exists
const exists = await tx.patient.findUnique({
where: { id },
});
if (exists) {
throw new Error(

`Patient with ID ${id} already exists in database.`,
);
}

const newPatientData = {};
const newPatientData = {};

for (const [key, value] of Object.entries(request.body)) {
if (value) newPatientData[key] = value.trim();
if (key === 'middleName' && value.length === 0) {
newPatientData[key] = null;
for (const [key, value] of Object.entries(request.body)) {
if (value) newPatientData[key] = value.trim();
if (key === 'middleName' && value.length === 0) {
newPatientData[key] = null;
}
if (key === 'dateOfBirth') newPatientData[key] = new Date(value);
}
if (key === 'dateOfBirth') newPatientData[key] = new Date(value);
}

let patient = await tx.patient.create({
data: {
...newPatientData,
createdById: userId,
updatedById: userId,
},
});
let patient = await tx.patient.create({
data: {
...newPatientData,
createdById: userId,
updatedById: userId,
},
});

return patient;
});
return patient;
});

reply.code(StatusCodes.CREATED).send(newPatient);
reply.code(StatusCodes.CREATED).send(newPatient);
} catch (error) {
if (error.message.includes('already exists')) {
return reply.status(StatusCodes.CONFLICT).send({
message: error.message,
});
}
throw error;
}
},
);
}

0 comments on commit 338c772

Please sign in to comment.