Skip to content

Commit

Permalink
Mongoose Integration and Database Performance Improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
ad956 committed Jul 3, 2024
1 parent 705a06a commit 0df63fd
Show file tree
Hide file tree
Showing 7 changed files with 94 additions and 89 deletions.
4 changes: 2 additions & 2 deletions app/api/city/route.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import dbConfig from "@utils/db";
import StateDocument from "@models/citystate_hospitals";
import CityStateHospital from "@models/citystate_hospitals";

export async function GET(req: Request) {
const { searchParams } = new URL(req.url);
Expand All @@ -10,7 +10,7 @@ export async function GET(req: Request) {
}

await dbConfig();
const stateDocument = await StateDocument.findOne({
const stateDocument = await CityStateHospital.findOne({
[state]: { $exists: true },
});

Expand Down
80 changes: 47 additions & 33 deletions app/api/receptionist/appointments/approve/route.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,51 @@
import dbConfig from "@utils/db";
import { decrypt } from "@sessions/sessionUtils";
import { ObjectId } from "mongodb";
import { BookedAppointment, Receptionist } from "@models/index";

// get approved appointments
export async function GET(request: Request) {
const session = request.headers.get("Authorization");
if (!session) {
return Response.json({ error: "Unauthorized" }, { status: 401 });
}

try {
const { patient_id } = await request.json();
const token = session.split("Bearer ")[1];
const decryptedUser = await decrypt(token);
const role = decryptedUser.user.role;

if (!role || role !== "receptionist") {
return new Response(
JSON.stringify({
error: "You do not have permission to access this resource",
}),
{
status: 401,
}
);
}

const { searchParams } = new URL(request.url);
const patient_id = searchParams.get("patient_id");

if (!patient_id) {
return new Response(JSON.stringify({ error: "Patient id is required" }), {
status: 400,
});
}

// Convert the patient_id string to an ObjectId
const patientObjectId = new ObjectId(patient_id);

const db = await dbConfig();
const bookedAppointmentsCollection = db.collection("bookedAppointments");
await dbConfig();

// Fetch the booked appointments for the specific patient and their receptionist
const appointments = await bookedAppointmentsCollection
.find({
patient_id: patientObjectId,
// Add the condition to filter by receptionist_id
receptionist_id: { $exists: true },
})
.toArray();
const appointments = await BookedAppointment.find({
patient_id: patientObjectId,
// Add the condition to filter by receptionist_id
receptionist_id: { $exists: true },
});

return new Response(JSON.stringify({ appointments }), {
status: 200,
Expand All @@ -32,6 +58,7 @@ export async function GET(request: Request) {
}
}

// approving appointments
export async function POST(request: Request) {
const session = request.headers.get("Authorization");
if (!session) {
Expand All @@ -45,15 +72,7 @@ export async function POST(request: Request) {
const token = session.split("Bearer ")[1];
const decryptedUser = await decrypt(token);

// Convert the patient_id string to an ObjectId
const patientObjectId = new ObjectId(patient_id);

const db = await dbConfig();

const receptionistCollection = db.collection("receptionist");
const bookedAppointmentsCollection = db.collection("bookedAppointments");

const receptionist = await receptionistCollection.findOne({
const receptionist = await Receptionist.findOne({
email: decryptedUser.user.email,
});

Expand All @@ -63,28 +82,23 @@ export async function POST(request: Request) {
});
}

// Update the approved status of the pending appointment for the specific patient to "approved"
const updateResult = await bookedAppointmentsCollection.updateOne(
{ approved: "pending", patient_id: patientObjectId },
{ $set: { approved: "approved", receptionist_id: receptionist._id } }
// update the approved status of the pending appointment for the specific patient to "approved"
const updatedAppointment = await BookedAppointment.findOneAndUpdate(
{ approved: "pending", patient_id },
{ $set: { approved: "approved", receptionist_id: receptionist._id } },
{ new: true } // returns the updated document instead of the original document
);

// Check if any document was updated
if (updateResult.modifiedCount === 0) {
// check if any document was updated
if (!updatedAppointment) {
return new Response(
JSON.stringify({
error: "No pending appointment found for the specified patient",
error: "Something went wrong while approving the appointment.",
}),
{ status: 404 }
{ status: 400 }
);
}

// Fetch the updated appointment for the specific patient
const updatedAppointment = await bookedAppointmentsCollection.findOne({
approved: "approved",
patient_id: patientObjectId,
});

return new Response(JSON.stringify({ appointment: updatedAppointment }), {
status: 200,
});
Expand Down
53 changes: 24 additions & 29 deletions app/api/receptionist/appointments/pending/route.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import dbConfig from "@utils/db";
import { decrypt } from "@sessions/sessionUtils";
import { Patient, BookedAppointment, Receptionist } from "@models/index";

export async function GET(request: Request) {
const session = request.headers.get("Authorization");
Expand All @@ -14,18 +15,11 @@ export async function GET(request: Request) {
const decryptedUser = await decrypt(token);
const email = decryptedUser.user.email;

const db = await dbConfig();
const receptionistCollection = db.collection("receptionist");
const bookedAppointmentsCollection = db.collection("bookedAppointments");
const patientCollection = db.collection("patient");
await dbConfig();

const projection = {
_id: 0,
current_hospital: 1,
};
const currentHospitalResult = await receptionistCollection.findOne(
const currentHospitalResult = await Receptionist.findOne(
{ email },
{ projection }
{ current_hospital: 1 }
);
if (!currentHospitalResult) {
return new Response(
Expand All @@ -35,11 +29,12 @@ export async function GET(request: Request) {
}
const currentHospitalId = currentHospitalResult.current_hospital;

const pendingAppointments = await bookedAppointmentsCollection
.find({ approved: "pending", "hospital.id": currentHospitalId })
.toArray();
const pendingAppointments = await BookedAppointment.find({
approved: "pending",
"hospital.id": currentHospitalId,
});

// empty array returned, If appointments are not found
// Empty array returned if appointments are not found
if (pendingAppointments.length === 0) {
return new Response(JSON.stringify({ patientDetails: [] }), {
status: 200,
Expand All @@ -50,19 +45,19 @@ export async function GET(request: Request) {
(appointment) => appointment.patient_id
);

const projection_patient = {
firstname: 1,
lastname: 1,
email: 1,
dob: 1,
gender: 1,
contact: 1,
profile: 1,
address: 1,
};
const patientDetails = await patientCollection
.find({ _id: { $in: patientIds } }, { projection: projection_patient })
.toArray();
const patientDetails = await Patient.find(
{ _id: { $in: patientIds } },
{
firstname: 1,
lastname: 1,
email: 1,
dob: 1,
gender: 1,
contact: 1,
profile: 1,
address: 1,
}
);

// Adding disease, note, date, and timing to each patient detail
const patientDetailsWithAdditionalInfo = patientDetails.map((patient) => {
Expand All @@ -72,14 +67,14 @@ export async function GET(request: Request) {
);
if (appointment) {
return {
...patient,
...patient.toObject(),
disease: appointment.disease,
note: appointment.note,
date: appointment.date,
timing: appointment.timing,
};
}
return patient;
return patient.toObject();
});

return new Response(
Expand Down
8 changes: 3 additions & 5 deletions app/api/receptionist/route.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import dbConfig from "@utils/db";
import { decrypt } from "@sessions/sessionUtils";
import Receptionist from "@models/receptionist";

export async function GET(request: Request) {
const session = request.headers.get("Authorization");
Expand All @@ -9,13 +10,10 @@ export async function GET(request: Request) {

try {
const token = session.split("Bearer ")[1];

const decryptedUser = await decrypt(token);

const email = decryptedUser.user.email;

const db = await dbConfig();
const collection = db.collection("receptionist");
await dbConfig();

const projection = {
_id: 1,
Expand All @@ -29,7 +27,7 @@ export async function GET(request: Request) {
dailyCount: 1,
};

const receptionistData = await collection.findOne(
const receptionistData = await Receptionist.findOne(
{ email },
{ projection }
);
Expand Down
13 changes: 6 additions & 7 deletions app/api/receptionist/scan/route.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,32 @@
import dbConfig from "@utils/db";
import { ObjectId } from "mongodb";
import { BookedAppointment, Patient, Receptionist } from "@models/index";

export async function POST(req: Request) {
try {
const { email } = await req.json();

console.log(email);

const db = await dbConfig();
const patientCollection = db.collection("patient");
const bookedAppointmentCollection = db.collection("bookedAppointments");
await dbConfig();

// const waitingCollection = db.collection("waiting");

const patient = await patientCollection.findOne({ email });
const patient = await Patient.findOne({ email });

if (!patient) {
return new Response(JSON.stringify({ error: "Patient not found" }), {
status: 404,
});
}

const appointment = await bookedAppointmentCollection.findOne({
const appointment = await BookedAppointment.findOne({
patient_id: new ObjectId(patient._id),
approved: "pending",
});

if (appointment) {
await bookedAppointmentCollection.updateOne(
await BookedAppointment.updateOne(
{ _id: appointment._id },
{ $set: { approved: "approved" } }
);
Expand All @@ -42,7 +42,6 @@ export async function POST(req: Request) {
);
} catch (error) {
console.error("Error scanning patient qr code:", error);
// Return an error response
return new Response(JSON.stringify({ error: "Internal Server Error" }), {
status: 500,
});
Expand Down
15 changes: 7 additions & 8 deletions app/api/states/route.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
import CityStateHospital from "@models/citystate_hospitals";
import dbConfig from "@utils/db";

export async function GET(req: Request) {
try {
const db = await dbConfig();
const collection = db.collection("citystate_hospitals");
await dbConfig();

const projection = { _id: 0 };
const cursor = await collection.find({}, { projection });
const statesArray = await CityStateHospital.find({}, { _id: 0 });

const states = await cursor.toArray();

if (!states || states.length === 0) {
if (!statesArray || statesArray.length === 0) {
return new Response("States not found", { status: 404 });
}

const stateNames = states.map((state) => Object.keys(state)[0]);
const stateNames = statesArray
.flatMap((state) => Object.keys(state.toObject()))
.filter((key) => key !== "cities");

return new Response(JSON.stringify(stateNames), { status: 200 });
} catch (error) {
Expand Down
10 changes: 5 additions & 5 deletions app/api/transactions/route.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import dbConfig from "@utils/db";
import { Transaction } from "@types";
import { Transaction as TransactionType } from "@types";
import { ObjectId } from "mongodb";
import Transaction from "@models/transaction";

// saving transaction details in db
export async function POST(req: Request) {
Expand All @@ -19,10 +20,9 @@ export async function POST(req: Request) {
description,
amount,
status,
}: Transaction = await req.json();
}: TransactionType = await req.json();

const db = await dbConfig();
const transaction_collection = db.collection("transactions");
await dbConfig();

const transactionData = {
transaction_id,
Expand All @@ -35,7 +35,7 @@ export async function POST(req: Request) {
status,
};

const res = await transaction_collection.insertOne(transactionData);
const res = await Transaction.create(transactionData);

if (!res)
return Response.json({
Expand Down

0 comments on commit 0df63fd

Please sign in to comment.