Skip to content

Commit

Permalink
Merge pull request #1 from ad956/feature/patient
Browse files Browse the repository at this point in the history
Refactor API Endpoints for Consistent Error Handling 🌟
  • Loading branch information
ad956 authored Sep 23, 2024
2 parents 1cb2480 + feb8a53 commit 760c836
Show file tree
Hide file tree
Showing 5 changed files with 100 additions and 91 deletions.
31 changes: 19 additions & 12 deletions app/api/patient/appointment/pending/route.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,30 @@
import dbConfig from "@utils/db";
import { Patient, BookedAppointment } from "@models/index";
import { dbConfig, errorHandler, STATUS_CODES } from "@utils/index";
import { authenticateUser } from "@lib/auth/authenticateUser";
import { Types } from "mongoose";
import { NextResponse } from "next/server";

export async function POST(req: Request) {
try {
const { hospital_id }: { hospital_id: string } = await req.json();
const authHeader = req.headers.get("Authorization");

const id = req.headers.get("x-user-id");
const role = req.headers.get("x-user-role");
const { id, role } = await authenticateUser(authHeader);

if (!id || !role) {
return Response.json(
{ error: "Missing user ID or role" },
{ status: 400 }
return errorHandler(
"Missing user ID or role",
STATUS_CODES.VALIDATION_ERROR
);
}

const patient_id = new Types.ObjectId(id);

await dbConfig();

const patient = await Patient.findById(patient_id);

if (!patient) {
return Response.json({ error: "Patient not found" }, { status: 404 });
return errorHandler("Patient not found", STATUS_CODES.NOT_FOUND);
}

// Checking if a pending appointment request exists with the hospital
Expand All @@ -34,12 +35,18 @@ export async function POST(req: Request) {
});

if (alreadyBookedAppointment) {
return Response.json({ hasPendingAppointment: true }, { status: 200 });
return NextResponse.json(
{ hasPendingAppointment: true },
{ status: 200 }
);
}

return Response.json({ hasPendingAppointment: false }, { status: 200 });
} catch (error) {
return NextResponse.json({ hasPendingAppointment: false }, { status: 200 });
} catch (error: any) {
console.error("Error checking pending appointments:", error);
return Response.json({ error: "Internal Server Error" }, { status: 500 });
return errorHandler(
error.message || "Internal Server Error",
STATUS_CODES.SERVER_ERROR
);
}
}
81 changes: 36 additions & 45 deletions app/api/patient/appointment/route.ts
Original file line number Diff line number Diff line change
@@ -1,46 +1,41 @@
import { dbConfig } from "@utils/index";
import { authenticateUser } from "@lib/auth/authenticateUser";
import { dbConfig, errorHandler, STATUS_CODES } from "@utils/index";
import { Types } from "mongoose";
import sendEmail from "@lib/sendemail";
import { render } from "@react-email/render";
import { AppointmentBookedTemplate } from "@lib/emails/templates";
import sendNotification from "@lib/novu";
import { Patient, BookedAppointment, Doctor } from "@models/index";
import { BookingAppointmentType } from "@pft-types/patient";
import { NextResponse } from "next/server";

// getting patients approved appointments
// getting patient's approved appointments
export async function GET(request: Request) {
try {
const id = request.headers.get("x-user-id");
const role = request.headers.get("x-user-role");
const authHeader = request.headers.get("Authorization");
const { id, role } = await authenticateUser(authHeader);

if (!id || !role) {
return Response.json(
{ error: "Missing user ID or role" },
{ status: 400 }
return errorHandler(
"Missing user ID or role",
STATUS_CODES.VALIDATION_ERROR
);
}

const patient_id = new Types.ObjectId(id);

await dbConfig();
const patient = await Patient.findById(patient_id);

const patient = await Patient.findById(patient_id);
if (!patient) {
return Response.json(
{ error: "Patient not found" },
{
status: 404,
}
);
return errorHandler("Patient not found", STATUS_CODES.NOT_FOUND);
}

let appointments = await BookedAppointment.find({
const appointments = await BookedAppointment.find({
patient_id: patient._id,
approved: "approved",
});

const doctorIds = appointments.map((appointment) => appointment.doctor_id);

const doctors = await Doctor.find(
{ _id: { $in: doctorIds } },
{ firstname: 1, lastname: 1, specialty: 1, profile: 1 }
Expand All @@ -62,16 +57,12 @@ export async function GET(request: Request) {
return appointmentObj;
});

return Response.json(updatedAppointments, {
status: 200,
});
} catch (error) {
return NextResponse.json(updatedAppointments, { status: 200 });
} catch (error: any) {
console.error("Error getting appointments:", error);
return Response.json(
{ error: "Internal Server Error" },
{
status: 500,
}
return errorHandler(
error.message || "Internal Server Error",
STATUS_CODES.SERVER_ERROR
);
}
}
Expand All @@ -89,24 +80,22 @@ export async function POST(req: Request) {
appointment_charge,
}: BookingAppointmentType = await req.json();

const id = req.headers.get("x-user-id");
const role = req.headers.get("x-user-role");
const authHeader = req.headers.get("Authorization");
const { id, role } = await authenticateUser(authHeader);

if (!id || !role) {
return Response.json(
{ error: "Missing user ID or role" },
{ status: 400 }
return errorHandler(
"Missing user ID or role",
STATUS_CODES.VALIDATION_ERROR
);
}

const patient_id = new Types.ObjectId(id);

await dbConfig();

const patient = await Patient.findById(patient_id);

if (!patient) {
return Response.json({ error: "Patient not found" }, { status: 404 });
return errorHandler("Patient not found", STATUS_CODES.NOT_FOUND);
}

const appointmentData = {
Expand All @@ -125,11 +114,12 @@ export async function POST(req: Request) {
};

const res = await BookedAppointment.create(appointmentData);

if (!res)
return Response.json({
error: "Error saving appointment info",
});
if (!res) {
return errorHandler(
"Error saving appointment info",
STATUS_CODES.SERVER_ERROR
);
}

const bookedAppointmentData = {
state,
Expand Down Expand Up @@ -167,14 +157,15 @@ export async function POST(req: Request) {
"appointment-request"
);

return Response.json(
{
msg: "Appointment request added successfully",
},
return NextResponse.json(
{ msg: "Appointment request added successfully" },
{ status: 200 }
);
} catch (error) {
} catch (error: any) {
console.error("Error adding appointment request:", error);
return Response.json({ error: "Internal Server Error" }, { status: 500 });
return errorHandler(
error.message || "Internal Server Error",
STATUS_CODES.SERVER_ERROR
);
}
}
25 changes: 14 additions & 11 deletions app/api/patient/medicalhistory/route.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,26 @@
import { Patient, Doctor, MedicalHistory, Hospital } from "@models/index";
import { Patient, MedicalHistory } from "@models/index";
import { Types } from "mongoose";
import { dbConfig, errorHandler, STATUS_CODES } from "@utils/index";
import { NextResponse } from "next/server";

export async function GET(request: Request) {
try {
const id = request.headers.get("x-user-id");
const role = request.headers.get("x-user-role");

if (!id || !role) {
return Response.json(
{ error: "Missing user ID or role" },
{ status: 400 }
return errorHandler(
"Missing user ID or role",
STATUS_CODES.VALIDATION_ERROR
);
}

const patient_id = new Types.ObjectId(id);
await dbConfig();

const patient = await Patient.findById(patient_id, { _id: 1 }).exec();
if (!patient) {
return Response.json({ error: "Patient not found" }, { status: 404 });
return errorHandler("Patient not found", STATUS_CODES.NOT_FOUND);
}

const medicalHistory = await MedicalHistory.find(
Expand Down Expand Up @@ -50,12 +53,12 @@ export async function GET(request: Request) {
disease: history.disease,
}));

return Response.json(formattedMedicalHistory);
} catch (error) {
console.error("Error fetching medical history of patient : ", error);
return Response.json(
{ error: "Failed to fetch medical history" },
{ status: 500 }
return NextResponse.json(formattedMedicalHistory, { status: 200 });
} catch (error: any) {
console.error("Error fetching medical history of patient:", error);
return errorHandler(
error.message || "Failed to fetch medical history",
STATUS_CODES.SERVER_ERROR
);
}
}
25 changes: 14 additions & 11 deletions app/api/patient/paymenthistory/route.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,29 @@
import dbConfig from "@utils/db";
import { Patient, Hospital, Transaction } from "@models/index";
import { dbConfig, errorHandler, STATUS_CODES } from "@utils/index";
import { Patient, Transaction } from "@models/index";
import { Types } from "mongoose";
import { NextResponse } from "next/server";

export async function GET(request: Request) {
try {
const id = request.headers.get("x-user-id");
const role = request.headers.get("x-user-role");

if (!id || !role) {
return Response.json(
{ error: "Missing user ID or role" },
{ status: 400 }
return errorHandler(
"Missing user ID or role",
STATUS_CODES.VALIDATION_ERROR
);
}

const patient_id = new Types.ObjectId(id);

await dbConfig();

const patient = await Patient.findById(patient_id);
if (!patient) {
return Response.json({ error: "Patient not found" }, { status: 404 });
return errorHandler("Patient not found", STATUS_CODES.NOT_FOUND);
}

// get all transactions where patient id matches
// get all transactions where patient ID matches
const transactions = await Transaction.find({
patient: patient._id,
})
Expand All @@ -45,9 +45,12 @@ export async function GET(request: Request) {
})
);

return Response.json(formattedTransactions, { status: 200 });
} catch (error) {
return NextResponse.json(formattedTransactions, { status: 200 });
} catch (error: any) {
console.error("Error fetching payment data:", error);
return Response.json({ error: "Internal Server Error" }, { status: 500 });
return errorHandler(
error.message || "Internal Server Error",
STATUS_CODES.SERVER_ERROR
);
}
}
29 changes: 17 additions & 12 deletions app/api/patient/route.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,23 @@
import dbConfig from "@utils/db";
import Patient from "@models/patient";
import { dbConfig, errorHandler, STATUS_CODES } from "@utils/index";
import { authenticateUser } from "@lib/auth/authenticateUser";
import { Types } from "mongoose";
import { NextResponse } from "next/server";

export async function GET(request: Request) {
const authHeader = request.headers.get("Authorization");

try {
const id = request.headers.get("x-user-id");
const role = request.headers.get("x-user-role");
const { id, role } = await authenticateUser(authHeader);

if (!id || !role) {
return Response.json(
{ error: "Missing user ID or role" },
{ status: 400 }
return errorHandler(
"Missing user ID or role",
STATUS_CODES.VALIDATION_ERROR
);
}

const patient_id = new Types.ObjectId(id);

await dbConfig();

const projection = {
Expand All @@ -25,15 +27,18 @@ export async function GET(request: Request) {
current_hospital: 0,
};

const patientData = await Patient.findById(patient_id, { projection });
const patientData = await Patient.findById(patient_id, projection);

if (!patientData) {
return Response.json({ error: "Patient not found" }, { status: 404 });
return errorHandler("Patient not found", STATUS_CODES.NOT_FOUND);
}

return Response.json(patientData);
} catch (error) {
return NextResponse.json(patientData, { status: 200 });
} catch (error: any) {
console.error("Error fetching patient data:", error);
return Response.json({ error: "Internal Server Error" }, { status: 500 });
return errorHandler(
error.message || "Internal Server Error",
STATUS_CODES.SERVER_ERROR
);
}
}

0 comments on commit 760c836

Please sign in to comment.