EthicsComputerCourses
Join training +91 90532 10052

Project: Hospital Appointment System

PERN Stack · Lesson 19 of 20 Project 16 min read Updated

In this project you will build the online appointment desk of Aashirwad Clinic, a small clinic in Gomti Nagar, Lucknow. Patients pick a doctor, a date and a free 15-minute slot. Doctors see their day as a schedule. Patients may cancel up to 2 hours before the visit. Most important of all, two patients can never get the same slot, even when they press "Book" in the same millisecond. You will prove that last promise with a real race.

What you should know first: Project: Expense Tracker, whose skeleton we reuse, plus Authentication with Sessions & JWT, Testing the PERN App and Deploying a PERN App. Database background: UUID, Enum & Range Types for ranges and exclusion constraints, and Transactions, Isolation & MVCC. Every output below is from our own run with PostgreSQL 18.6, Node.js 22 and Chrome; as in earlier lessons, only port numbers were changed.

What you will build

FeatureWhere it lives
Doctors with weekly OPD hours, such as Monday to Saturday 10:00-13:00doctors and weekly_hours tables
Free and taken slots for any doctor and dateGET /api/doctors/:id/slots?date=2026-11-19
Booking, with no double booking under any loadPOST /api/appointments plus an exclusion constraint
Patient and doctor rolesrole column, role in the JWT, requireRole()
Cancel up to 2 hours before the startPOST /api/appointments/:id/cancel
The doctor's day scheduleGET /api/schedule?date=2026-11-19, SchedulePage.jsx

Think of the OPD register at a clinic's reception: one line per time slot. When one receptionist takes bookings, nothing goes wrong. Now give the clinic two receptionists and two phones. Both look at the register, both see 11:15 empty, and both write a name on the same line. A web server is a reception desk with hundreds of phones, so "look, then write" is not safe. This project shows the failure and then fixes it inside PostgreSQL.

Step 1: start from the skeleton

Copy the finished Expense Tracker into clinic/, without node_modules, dist and .git, and run npm install. Keep config, the pool, errors, auth, rate limits, migrate.js, the API client, useApi, the auth pages and the test helpers. Delete the budget, report, expense and CSV files. Rename the cookie to clinic_token. Then create roles and a database as the postgres superuser, exactly as before:

SQL
CREATE ROLE clinic_owner LOGIN PASSWORD 'choose-a-long-owner-password';
CREATE ROLE clinic_app LOGIN PASSWORD 'choose-a-long-app-password';
CREATE DATABASE clinic OWNER clinic_owner;
\c clinic
ALTER DEFAULT PRIVILEGES FOR ROLE clinic_owner IN SCHEMA public
  GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO clinic_app;

Step 2: the schema

db/migrations/001_schema.sql holds four tables. Here are the parts that matter:

SQL
CREATE TABLE users (
  id            integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email         text NOT NULL UNIQUE CHECK (email = lower(email)),
  name          text NOT NULL CHECK (length(name) BETWEEN 1 AND 60),
  password_hash text NOT NULL,
  role          text NOT NULL DEFAULT 'patient' CHECK (role IN ('patient', 'doctor')),
  created_at    timestamptz NOT NULL DEFAULT now()
);

-- doctors: user_id (UNIQUE), speciality, room, slot_minutes CHECK IN (10, 15, 20, 30)

-- OPD hours that repeat every week. weekday: 1 = Monday ... 7 = Sunday (isodow).
CREATE TABLE weekly_hours (
  doctor_id integer NOT NULL REFERENCES doctors (id) ON DELETE CASCADE,
  weekday   smallint NOT NULL CHECK (weekday BETWEEN 1 AND 7),
  starts    time NOT NULL,
  ends      time NOT NULL CHECK (ends > starts),
  PRIMARY KEY (doctor_id, weekday, starts)
);

CREATE TABLE appointments (
  id           integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  doctor_id    integer NOT NULL REFERENCES doctors (id),
  patient_id   integer NOT NULL REFERENCES users (id),
  starts_at    timestamptz NOT NULL,
  ends_at      timestamptz NOT NULL CHECK (ends_at > starts_at),
  reason       text NOT NULL DEFAULT '' CHECK (length(reason) <= 200),
  status       text NOT NULL DEFAULT 'booked' CHECK (status IN ('booked', 'cancelled')),
  cancelled_at timestamptz,
  created_at   timestamptz NOT NULL DEFAULT now()
);

We store hours, not slots. A slot table would need a new row for every doctor, every day, for ever. Instead, slots are calculated from weekly_hours when someone asks. Appointments use timestamptz, an exact moment in time, and a cancelled appointment stays in the table with its status, because a clinic needs that history. The development seed adds Dr. Farhan Siddiqui (General Medicine, Room 2, 15-minute slots, Monday to Saturday 10:00-13:00), Dr. Ananya Mishra (Paediatrics, Room 5, 20-minute slots, Monday, Wednesday and Friday 17:00-19:00), and two patients, Rohan Verma and Isha Srivastava.

Step 3: roles in the token

The JWT from the auth lesson now carries the role too, so a route can check it without a database query. In middleware/auth.js, setAuthCookie(res, user) signs { sub: String(user.id), role: user.role }, and requireAuth copies payload.role into req.role. One small middleware then guards whole routers:

JavaScript
// Use after requireAuth: requireRole("doctor") lets only doctors through.
export function requireRole(role) {
  return (req, res, next) => {
    if (req.role !== role) {
      throw new HttpError(403, "FORBIDDEN", `Only a ${role} can do this.`);
    }
    next();
  };
}

In app.js: app.use("/api/schedule", requireAuth, requireRole("doctor"), scheduleRouter). The booking routes use requireRole("patient"). 401 means "we do not know who you are"; 403 means "we know, and the answer is no".

The most important line is one that is missing. createUser() inserts only email, name and hash, so the database default makes every new account a patient. Doctors are added by the clinic, never through the sign-up form. We tried to cheat anyway:

Terminal
curl -s -X POST http://localhost:4000/api/auth/register -H "Content-Type: application/json" \
  -d '{"email":"kabir@example.in","name":"Kabir Khan","password":"a-long-kabir-password","role":"doctor"}'
Output
{"data":{"id":165,"email":"kabir@example.in","name":"Kabir Khan","role":"patient"}}

Copying every field of the request body into the database is called mass assignment, and it is how users quietly make themselves admins. The id is 165 because the race tests in Step 5 created many accounts first. A role inside a token also lasts until the token expires, so we shortened its life to one day; a demoted user loses the role by the next morning.

Step 4: slots from weekly hours

daySlots(doctorId, date) in src/data/doctors.js turns hours into slots with generate_series and marks each one as past, booked or free:

JavaScript
export async function daySlots(doctorId, date) {
  const { rows } = await query(
    `SELECT to_char(s.starts_at AT TIME ZONE 'Asia/Kolkata', 'HH24:MI') AS time,
            s.starts_at, s.starts_at + d.len AS ends_at,
            CASE WHEN s.starts_at <= now() THEN 'past'
                 WHEN a.id IS NOT NULL THEN 'booked'
                 ELSE 'free' END AS state,
            a.id AS appointment_id, p.name AS patient, a.reason
     FROM (SELECT id, slot_minutes * interval '1 minute' AS len
           FROM doctors WHERE id = $1) AS d
     JOIN weekly_hours h
       ON h.doctor_id = d.id AND h.weekday = extract(isodow FROM $2::date)
     CROSS JOIN LATERAL generate_series($2::date + h.starts, $2::date + h.ends - d.len, d.len) AS g (local_start)
     CROSS JOIN LATERAL (SELECT g.local_start AT TIME ZONE 'Asia/Kolkata' AS starts_at) AS s
     LEFT JOIN appointments a
       ON a.doctor_id = d.id AND a.status = 'booked'
      AND tstzrange(a.starts_at, a.ends_at) && tstzrange(s.starts_at, s.starts_at + d.len)
     LEFT JOIN users p ON p.id = a.patient_id
     ORDER BY s.starts_at`,
    [doctorId, date],
  );
  return rows;
}

Read it in parts. $2::date + h.starts adds a time to a date, giving 2026-11-19 10:00 with no time zone. generate_series steps from the first start to the last start, 15 minutes at a time. AT TIME ZONE 'Asia/Kolkata' then says "this is clinic time" and turns each one into a real moment. Writing the zone in SQL keeps slots correct even on a cloud server set to UTC. tstzrange(a, b) is the range from a up to, but not including, b, and && means "overlaps", so a 10:15-10:30 booking touches the 10:15 slot but not 10:30. LATERAL Joins & generate_series explains the joins.

The patient's route maps booked to taken and drops the name and reason; patients must never see who else visits the doctor. Rohan asked for Thursday, after Isha had booked 10:45:

Terminal
curl -s -b rohan.txt "http://localhost:4000/api/doctors/1/slots?date=2026-11-19"
Output
{"data":[{"time":"10:00","state":"free"},{"time":"10:15","state":"free"},{"time":"10:30","state":"free"},{"time":"10:45","state":"taken"},{"time":"11:00","state":"free"},{"time":"11:15","state":"free"},{"time":"11:30","state":"free"},{"time":"11:45","state":"free"},{"time":"12:00","state":"free"},{"time":"12:15","state":"free"},{"time":"12:30","state":"free"},{"time":"12:45","state":"free"}]}

Twelve slots: 10:00 to 12:45. A Sunday, when Dr. Farhan has no hours, answers {"data":[]}.

Step 5: book the obvious way, and watch it fail

The booking route validates the body, finds the slot with daySlots(), refuses a past or missing slot with 400 and a taken one with 409, then inserts:

JavaScript
const slots = await doctors.daySlots(value.doctorId, value.date);
const slot = slots.find((s) => s.time === value.time);
if (!slot || slot.state === "past") {
  throw new HttpError(400, "VALIDATION_FAILED", "Some fields need fixing.", {
    time: "This doctor has no open slot at that time.",
  });
}
if (slot.state === "booked") {
  throw new HttpError(409, "SLOT_TAKEN", "Someone has just booked this slot. Please choose another time.");
}
const booked = await appointments.book({
  doctorId: value.doctorId, patientId: req.userId,
  startsAt: slot.starts_at, endsAt: slot.ends_at, reason: value.reason,
});
res.status(201).json({ data: { ...booked, date: value.date, time: value.time } });

The server uses the slot's own starts_at and ends_at, never times sent by the browser, so nobody can book 10:07 or a two-hour slot. Clicking once at a time, this works. Now the two receptionists. scripts/race.js registers 20 patients, then sends 20 bookings for one slot at the same moment:

JavaScript
// Open 20 connections first, so the bookings below do not queue behind TCP handshakes.
await Promise.all(cookies.map(() => fetch(`${BASE}/api/health`).then((res) => res.text())));

// All 20 requests leave together; nobody waits for anybody.
const statuses = await Promise.all(
  cookies.map((cookie) =>
    fetch(`${BASE}/api/appointments`, {
      method: "POST",
      headers: { "Content-Type": "application/json", Cookie: cookie },
      body: JSON.stringify({ doctorId: 1, date, time, reason: "Fever since Sunday" }),
    }).then((res) => res.status),
  ),
);

The 20 registrations run one by one, because the register limiter from the security lesson also counts requests that are still running. Our first try fired straight away and got 429s. Then the race:

Terminal
API_URL=http://localhost:4000 node scripts/race.js 2026-11-18 10:30
Output
2026-11-18 10:30 with Dr. Farhan: { '201': 3, '409': 17 }

Then we listed the appointments in psql, with the time shown in clinic time:

Output
 id |     patient     |     slot     | status
----+-----------------+--------------+--------
  1 | Race patient 1  | 18 Nov 10:30 | booked
  2 | Race patient 11 | 18 Nov 10:30 | booked
  3 | Race patient 12 | 18 Nov 10:30 | booked
(3 rows)

Three patients now expect Dr. Farhan at 10:30. Patients 11 and 12 read the slot as free while patient 1's insert had not yet committed. The check is correct; it is simply too early. In earlier test runs we saw 1, 3 and 6 winners for one slot. A race does not fail every time, which is why it slips through testing and then fails on a busy Monday.

Step 6: let PostgreSQL refuse the second booking

Only the database sees every insert, so the rule must live there. A unique index on (doctor_id, starts_at) would stop two identical start times. An exclusion constraint goes further: no two rows may have the same doctor and overlapping time ranges. Add db/migrations/002_no_double_booking.sql:

SQL
BEGIN;

-- Lets a GiST index compare plain integers with =, next to the range overlap &&.
CREATE EXTENSION IF NOT EXISTS btree_gist;

-- No two live bookings for the same doctor may overlap in time.
ALTER TABLE appointments ADD CONSTRAINT appointments_no_double_booking
  EXCLUDE USING gist (doctor_id WITH =, tstzrange(starts_at, ends_at) WITH &&)
  WHERE (status = 'booked');

-- A patient cannot be in two consulting rooms at once either.
ALTER TABLE appointments ADD CONSTRAINT appointments_patient_free
  EXCLUDE USING gist (patient_id WITH =, tstzrange(starts_at, ends_at) WITH &&)
  WHERE (status = 'booked');

COMMIT;

WHERE (status = 'booked') makes it a partial constraint, so cancelled rows never block a slot. btree_gist is a trusted extension in PostgreSQL 18.6, so clinic_owner may install it. We ran the file with psql first, and PostgreSQL refused, because our table already broke the rule:

Output
psql:db/migrations/002_no_double_booking.sql:10: ERROR:  could not create exclusion constraint "appointments_no_double_booking"
DETAIL:  Key (doctor_id, tstzrange(starts_at, ends_at))=(1, ["2026-11-18 10:30:00+05:30","2026-11-18 10:45:00+05:30")) conflicts with key (doctor_id, tstzrange(starts_at, ends_at))=(1, ["2026-11-18 10:30:00+05:30","2026-11-18 10:45:00+05:30")).

A real clinic would phone the extra patients. We kept the first booking of each clash and cancelled the rest:

SQL
UPDATE appointments a SET status = 'cancelled', cancelled_at = now()
WHERE a.status = 'booked' AND EXISTS (
  SELECT 1 FROM appointments b
  WHERE b.doctor_id = a.doctor_id AND b.status = 'booked' AND b.id < a.id
    AND tstzrange(b.starts_at, b.ends_at) && tstzrange(a.starts_at, a.ends_at)
);

That printed UPDATE 2, and npm run migrate -w server then printed applied 002_no_double_booking.sql. A violated exclusion constraint raises error code 23P01 with err.constraint set, so errors.js gains a second map that answers 409 instead of 400:

JavaScript
// Exclusion constraints: the request was fine, but the time is no longer free.
const CONFLICTS = {
  appointments_no_double_booking: ["SLOT_TAKEN", "Someone has just booked this slot. Please choose another time."],
  appointments_patient_free: ["PATIENT_BUSY", "You already have an appointment at this time."],
};

The error handler checks CONFLICTS[err.constraint] before the field map. Now five races in a row:

Output
2026-11-18 10:45 with Dr. Farhan: { '201': 1, '409': 19 }
2026-11-18 11:00 with Dr. Farhan: { '201': 1, '409': 19 }
2026-11-18 11:15 with Dr. Farhan: { '201': 1, '409': 19 }
2026-11-18 11:30 with Dr. Farhan: { '201': 1, '409': 19 }
2026-11-18 11:45 with Dr. Farhan: { '201': 1, '409': 19 }

To be sure the database did the work, we switched off the slot.state === "booked" check in the route, restarted, and raced two more slots. Both ended { '201': 1, '409': 19 }, every refusal now coming from PostgreSQL. Keep the check in the real code: it gives the usual case a quick answer, and the constraint is the guarantee. Overlaps are caught too, which a unique index on the start time would miss. A 10:20-10:35 insert in psql against Rohan's 10:15 booking:

Output
ERROR:  23P01: conflicting key value violates exclusion constraint "appointments_no_double_booking"
DETAIL:  Key (doctor_id, tstzrange(starts_at, ends_at))=(1, ["2026-11-19 10:20:00+05:30","2026-11-19 10:35:00+05:30")) conflicts with existing key (doctor_id, tstzrange(starts_at, ends_at))=(1, ["2026-11-19 10:15:00+05:30","2026-11-19 10:30:00+05:30")).

Step 7: cancel, but not at the last minute

The cancel rule fits in one UPDATE, so two clicks can never both win:

JavaScript
export const CANCEL_WINDOW = "2 hours";

export async function cancel(id, userId) {
  const { rowCount } = await query(
    `UPDATE appointments a SET status = 'cancelled', cancelled_at = now()
     WHERE a.id = $1 AND a.status = 'booked'
       AND ((a.patient_id = $2 AND a.starts_at > now() + $3::interval)
         OR (a.doctor_id = (SELECT id FROM doctors WHERE user_id = $2) AND a.starts_at > now()))`,
    [id, userId, CANCEL_WINDOW],
  );
  return rowCount === 1;
}

A patient may cancel their own booking until 2 hours before it starts. A doctor may cancel their own appointments until they start, for an emergency. The window is a placeholder, cast with ::interval, and now() comes from the database clock, so a wrong laptop clock changes nothing. When no row changes, the route runs findOwn() to explain why: 404 when the appointment is not yours, so ids reveal nothing, otherwise 409. The list query returns "canCancel" from the same condition, so the button and the server agree. Our requests:

RequestAnswer
Isha cancels Rohan's appointment 83404 "That appointment was not found."
Rohan cancels 83{"data":{"id":83,"status":"cancelled"}}
Rohan cancels 83 again409 "This appointment is already cancelled."
Rohan books the same 10:15 slot again201, id 86: the cancelled row does not block it
Dr. Farhan tries to book403 "Only a patient can do this."
Rohan opens /api/schedule403 "Only a doctor can do this."

The 2-hour case needs an appointment starting soon, so it lives in the tests in Step 10.

Step 8: the doctor's day

GET /api/schedule?date= finds the doctor's id from req.userId, so a doctor can only ever see their own day, and returns every slot with the patient and reason. SchedulePage.jsx keeps the date in the URL and hands the data to DaySchedule. Here it is with the real answer for Thursday 19 November, shortened to eight slots:

React JSXOpen in editor
import { createRoot } from "react-dom/client";

// From our GET /api/schedule?date=2026-11-19 as Dr. Farhan (8 of 12 slots shown)
const day = {
  date: "2026-11-19",
  booked: 5,
  slots: [
    { time: "10:00", state: "free", patient: null, reason: null },
    { time: "10:15", state: "booked", patient: "Rohan Verma", reason: "Cough and mild fever for four days" },
    { time: "10:30", state: "free", patient: null, reason: null },
    { time: "10:45", state: "booked", patient: "Isha Srivastava", reason: "Follow-up with blood test report" },
    { time: "11:00", state: "booked", patient: "Isha Srivastava", reason: "Back pain after a fall" },
    { time: "11:15", state: "free", patient: null, reason: null },
    { time: "11:30", state: "booked", patient: "Rohan Verma", reason: "Blood pressure check" },
    { time: "11:45", state: "booked", patient: "Rohan Verma", reason: "Blood pressure check" },
  ],
};

// "2026-11-19" -> "Thu, 19 Nov, 2026" without any time zone shift
function longDate(isoDate) {
  const [y, m, d] = isoDate.split("-").map(Number);
  return new Date(Date.UTC(y, m - 1, d)).toLocaleDateString("en-IN", {
    weekday: "short", day: "numeric", month: "short", year: "numeric", timeZone: "UTC",
  });
}

function DaySchedule({ day }) {
  const free = day.slots.filter((s) => s.state === "free").map((s) => s.time);
  console.log(`${longDate(day.date)}: free at ${free.join(", ")}`);
  return (
    <>
      <p>{longDate(day.date)}: {day.booked} booked.</p>
      <table>
        <thead><tr><th scope="col">Time</th><th scope="col">Patient</th><th scope="col">Reason</th></tr></thead>
        <tbody>
          {day.slots.map((s) => (
            <tr key={s.time} style={{ color: s.state === "booked" ? "inherit" : "#6b7785" }}>
              <th scope="row">{s.time}</th>
              <td>{s.state === "booked" ? s.patient : s.state === "past" ? "-" : "Free"}</td>
              <td>{s.reason}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </>
  );
}

createRoot(document.getElementById("root")).render(<DaySchedule day={day} />);
Output
Thu, 19 Nov, 2026: free at 10:00, 10:30, 11:15

Patients' names and reasons are text in JSX, so React escapes them; a reason such as <img src=x onerror=...> shows as plain characters.

Step 9: the booking page in Chrome

BookPage.jsx keeps the doctor and date in the URL (/book?doctor=1&date=2026-11-19), shows the slots as buttons, disables taken and past ones, and asks for an optional reason. Its submit handler treats a 409 as normal news:

React JSX
async function handleSubmit(event) {
  event.preventDefault();
  const reason = String(new FormData(event.currentTarget).get("reason"));
  try {
    await api("/api/appointments", {
      method: "POST",
      body: { doctorId: Number(doctorId), date, time: chosen, reason },
    });
    setMessage({ ok: true, text: `Booked: ${longDate(date)} at ${chosen}.` });
  } catch (err) {
    // 409 SLOT_TAKEN: someone was faster. Show it and load the fresh slots.
    setMessage({ ok: false, text: err.details?.time ?? err.message });
  }
  setChosen(null);
  setVersion((v) => v + 1);
}

A RequireRole route guard sends doctors to /schedule and patients to /book, and the header shows "My day" or "Book" and "My appointments". The server still checks every request; the guard only keeps menus tidy. We built the client, started the server in production mode and used it in Chrome:

You doScreen
Log in as Isha at /book?doctor=1&date=2026-11-19Twelve buttons; "10:15 (taken)" and "10:45 (taken)" are disabled
Click 11:00, type "Back pain after a fall", Book"Booked: Thu, 19 Nov, 2026 at 11:00." and 11:00 turns "(taken)"
Click 11:45; Rohan books 11:45 from curl; then BookPOST answers 409, the page says "Someone has just booked this slot. Please choose another time." and 11:45 shows "(taken)"
Open My appointmentsThree rows, each with a Cancel button
Log in as Dr. Farhan, open My day for 19 Nov"5 of 12 slots booked." and the table from Step 8

Step 10: test the promises

server/test/appointments.test.js creates a test doctor who works every day, 10:00-13:00, and picks tomorrow's date in clinic time, so the tests never go stale:

JavaScript
it("lets exactly one of ten patients book the same slot", async () => {
  const patients = [];
  for (let i = 1; i <= 10; i++) patients.push(await signUp(`Patient${i}`));
  const results = await Promise.all(patients.map((p) =>
    p.post("/api/appointments").send({ doctorId: doctor.id, date: tomorrow, time: "11:30" })));
  const statuses = results.map((r) => r.status).toSorted();
  assert.deepEqual(statuses, [201, 409, 409, 409, 409, 409, 409, 409, 409, 409]);
});

The window test inserts an appointment directly with starts_at = now() + interval '1 hour', expects the patient's cancel to answer 409 TOO_LATE_TO_CANCEL, then lets the doctor cancel it with 200:

Output
▶ appointments
  ✔ lets exactly one of ten patients book the same slot (19916.958ms)
  ✔ frees a cancelled slot for the next patient (5154.4604ms)
  ✔ closes cancellation for patients 2 hours before the start (2069.8975ms)
  ✔ keeps roles apart (7389.4215ms)
✔ appointments (34538.3701ms)
▶ login rate limit
  ✔ answers 429 after five failed logins (8312.4234ms)
✔ login rate limit (8323.5262ms)
ℹ tests 5
ℹ suites 2
ℹ pass 5
ℹ fail 0

The times are high because every sign-up hashes a password with argon2, which is slow on purpose. The release is the deployment lesson's, with clinic names: build, migrate as clinic_owner, restart the systemd unit, check /api/health.

Ideas to extend it

  • Let the reception desk book for walk-in patients with a third role, staff.
  • Send an SMS or email reminder the evening before, from a scheduled job.
  • Add a "no-show" status, and keep it out of the exclusion constraint's WHERE.

Interview questions

1. How do you stop two users booking the same slot at the same time?

Put the rule in the database. A unique index on (doctor_id, starts_at) stops identical starts, and an exclusion constraint with btree_gist stops any overlap. The API maps the violation to 409. An application-only "check, then insert" has a race window between the two steps.

2. What is an exclusion constraint?

It generalises a unique constraint: no two rows may match on every listed operator. EXCLUDE USING gist (doctor_id WITH =, tstzrange(starts_at, ends_at) WITH &&) means no two rows with the same doctor and overlapping times. A WHERE clause makes it partial, for example only for booked rows.

3. Why must the server ignore a role field in the sign-up body?

Otherwise anyone could register as a doctor or admin. This is mass assignment. Accept only the fields a form may set, and give roles through a separate, protected path.

4. How do you handle time zones for a clinic's slots?

Store moments as timestamptz, keep opening hours as local time, and convert with AT TIME ZONE 'Asia/Kolkata' in SQL. Then the server's own time zone and the visitor's browser cannot shift a slot.

Key points

  • Store weekly hours and calculate slots with generate_series; store appointments as timestamptz ranges.
  • "Check, then insert" races under load: our run booked one slot three times.
  • An exclusion constraint with btree_gist refuses overlapping bookings in every case; WHERE (status = 'booked') lets cancelled slots be booked again.
  • Map error 23P01 by constraint name to a 409, and let the React page reload the slots.
  • Put the role in the token and check it with requireRole(); sign-up never accepts a role.
  • One UPDATE with all the rules handles the 2-hour cancellation window; now() comes from the database.
  • Prove concurrency rules with a real race script and a test that fires requests together.

Exercise

Dr. Farhan will attend a medical camp in Barabanki on Friday. Add leave days. Write migration 003_leave_days.sql with a leave_days (doctor_id, day) table, change daySlots() so a leave day has no slots, and add POST /api/schedule/leave with { "date": "2026-11-20" } for doctors. If patients are already booked that day, answer 409 with how many, so the clinic can call them first.

Show solution
SQL
-- 003_leave_days.sql: days when a doctor does not sit in the OPD.
BEGIN;

CREATE TABLE leave_days (
  doctor_id integer NOT NULL REFERENCES doctors (id) ON DELETE CASCADE,
  day       date NOT NULL,
  PRIMARY KEY (doctor_id, day)
);

COMMIT;
JavaScript
// src/data/doctors.js: in daySlots(), extend the weekly_hours join:
//   AND NOT EXISTS (SELECT 1 FROM leave_days l WHERE l.doctor_id = d.id AND l.day = $2::date)

export async function addLeaveDay(doctorId, date) {
  return transaction(async (client) => {
    const { rows } = await client.query(
      `SELECT count(*)::int AS booked FROM appointments
       WHERE doctor_id = $1 AND status = 'booked'
         AND (starts_at AT TIME ZONE 'Asia/Kolkata')::date = $2::date`,
      [doctorId, date],
    );
    if (rows[0].booked > 0) return { added: false, booked: rows[0].booked };
    await client.query(
      "INSERT INTO leave_days (doctor_id, day) VALUES ($1, $2) ON CONFLICT DO NOTHING",
      [doctorId, date],
    );
    return { added: true, booked: 0 };
  });
}

// src/routes/schedule.js (already behind requireAuth and requireRole("doctor"))
router.post("/leave", async (req, res) => {
  const date = parseDate(req.body?.date);
  if (!date) {
    throw new HttpError(400, "VALIDATION_FAILED", "Some fields need fixing.", {
      date: "Use a date in the form YYYY-MM-DD.",
    });
  }
  const result = await doctors.addLeaveDay(await doctors.doctorIdForUser(req.userId), date);
  if (!result.added) {
    throw new HttpError(409, "DAY_HAS_BOOKINGS",
      `${result.booked} patient(s) are booked on ${date}. Cancel or move them first.`);
  }
  res.status(201).json({ data: { date } });
});

In our run, leave for 19 November answered "5 patient(s) are booked on 2026-11-19. Cancel or move them first.", leave for 20 November answered 201, and Friday's slots became {"data":[]}. A booking that arrives in the same instant as the leave could still slip in; the doctor's day view would show it.

Quick Quiz

1. Twenty requests book the same free slot at once, and the route checks the slot before inserting. Without a constraint, what can happen?

2. What does WHERE (status = 'booked') do in the exclusion constraint?

3. Why is btree_gist needed?

4. A patient's account sends "role": "doctor" while registering. What should happen?

Learn PERN Stack with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call