Booking systems look easy and are famous for hiding hard problems. Two guests must never get the same room on the same night. Dates have edge cases. Payments fail halfway. Cancellations have rules. This project is a strong one for a portfolio because its logic is the kind that real companies struggle with, and because it is easy to test: you give it dates, and you check the answer.
What you will build
- Admins add rooms with a number, a type and a price per night in cents.
GET /api/availability?checkIn=...&checkOut=...lists free rooms.POST /api/reservationsreserves a room, charges the payment provider and confirms.POST /api/reservations/:id/cancelapplies the refund rule.- Clear errors for bad dates, taken rooms and failed payments.
Design decisions before any code
Dates are plain text in the form 2026-12-24, checked with a pattern and a real calendar check. A stay has a check-in day and a check-out day, and the number of nights is the difference. The most important rule is the overlap rule, and it is easy to get wrong, so it deserves a precise sentence: two stays overlap when each one starts before the other one ends. The check-out day is free, so a guest can leave in the morning and the next guest can arrive the same day, and the test checks exactly that.
Money is in cents, the total is the nights multiplied by the price, and the price comes from the server's room record. The clock is injected, so the test can make a stay start in 30 hours or in 10 days without waiting.
- Make a folder and open it in a terminal. Run
npm init -y, then openpackage.jsonand add"type": "module"so thatimportworks. - Install what the lesson needs:
npm install express jsonwebtoken. - Copy
p-kit.js,p07-hotel.jsandp07.test.jsinto the folder. The sharedp-kit.jsis in Project 1. - Install the test tools with
npm install -D supertest, then runnode --test p07.test.js.
Read overlaps and isFree first. The reservation route then applies them in a clear order: validate, check room, check dates, check availability, charge, confirm.
// Project 7: hotel booking. Rooms, availability by date range, reservations, cancellation and payment.
import express from 'express';
import { AppError, requireAuth, requireRole, errorHandler, notFoundHandler } from './p-kit.js';
const DAY = 86_400_000;
const parseDate = (value) => {
const date = new Date(`${value}T00:00:00Z`);
if (!/^\d{4}-\d{2}-\d{2}$/.test(String(value)) || Number.isNaN(date.getTime())) throw new AppError('Dates must look like 2026-12-24', 422);
return date;
};
// Two stays overlap when each starts before the other ends. Check-out day is free for the next guest.
export const overlaps = (aStart, aEnd, bStart, bEnd) => aStart < bEnd && bStart < aEnd;
export function createApp({ payments = { charge: async () => ({ ok: true, id: 'pay_demo' }) }, now = () => new Date() } = {}) {
const app = express();
app.use(express.json());
const auth = requireAuth();
const rooms = new Map();
const reservations = [];
app.post('/api/rooms', auth, requireRole('admin'), (req, res) => {
const { number, type, pricePerNightCents } = req.body ?? {};
if (!number || !type || !Number.isInteger(pricePerNightCents) || pricePerNightCents < 1) throw new AppError('number, type and pricePerNightCents are required', 422);
const room = { id: rooms.size + 1, number, type, pricePerNightCents };
rooms.set(room.id, room);
res.status(201).json(room);
});
const isFree = (roomId, start, end) =>
!reservations.some((r) => r.roomId === roomId && r.status === 'confirmed' && overlaps(start, end, new Date(r.checkIn), new Date(r.checkOut)));
app.get('/api/availability', (req, res) => {
const start = parseDate(req.query.checkIn);
const end = parseDate(req.query.checkOut);
if (end <= start) throw new AppError('checkOut must be after checkIn', 422);
res.json([...rooms.values()].filter((room) => isFree(room.id, start, end) && (!req.query.type || room.type === req.query.type)));
});
app.post('/api/reservations', auth, async (req, res) => {
const room = rooms.get(Number(req.body?.roomId));
if (!room) throw new AppError('Room not found', 404);
const start = parseDate(req.body.checkIn);
const end = parseDate(req.body.checkOut);
if (end <= start) throw new AppError('checkOut must be after checkIn', 422);
if (start < new Date(now().toISOString().slice(0, 10))) throw new AppError('checkIn cannot be in the past', 422);
if (!isFree(room.id, start, end)) throw new AppError('Room is not available for those dates', 409);
const nights = (end - start) / DAY;
const totalCents = nights * room.pricePerNightCents;
// Reserve first, then charge, so two people cannot both pay for the same room.
const reservation = { id: reservations.length + 1, roomId: room.id, userId: req.user.id, checkIn: req.body.checkIn, checkOut: req.body.checkOut, nights, totalCents, status: 'confirmed' };
reservations.push(reservation);
const payment = await payments.charge({ amountCents: totalCents, reservationId: reservation.id });
if (!payment.ok) { reservation.status = 'payment_failed'; throw new AppError('Payment failed', 402); }
reservation.paymentId = payment.id;
res.status(201).json(reservation);
});
// Cancellation rule: free until 48 hours before check-in, after that 50% refund.
app.post('/api/reservations/:id/cancel', auth, (req, res) => {
const reservation = reservations.find((r) => r.id === Number(req.params.id));
if (!reservation || (reservation.userId !== req.user.id && req.user.role !== 'admin')) throw new AppError('Reservation not found', 404);
if (reservation.status !== 'confirmed') throw new AppError('Reservation is not active', 409);
const hoursLeft = (new Date(reservation.checkIn) - now()) / 3_600_000;
reservation.status = 'cancelled';
reservation.refundCents = hoursLeft >= 48 ? reservation.totalCents : Math.floor(reservation.totalCents / 2);
res.json(reservation);
});
app.use(notFoundHandler, errorHandler);
return app;
}
Three tests: the overlap rule on its own, a full run of availability, booking, double booking and refunds, and a late cancellation together with a failed payment.
import test from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { createApp, overlaps } from './p07-hotel.js';
import { signToken } from './p-kit.js';
const as = (id, role = 'guest') => ({ Authorization: `Bearer ${signToken({ id, role, name: `u${id}` })}` });
test('date overlap rule', () => {
const d = (s) => new Date(`${s}T00:00:00Z`);
assert.equal(overlaps(d('2026-12-01'), d('2026-12-05'), d('2026-12-04'), d('2026-12-08')), true);
assert.equal(overlaps(d('2026-12-01'), d('2026-12-05'), d('2026-12-05'), d('2026-12-08')), false); // same-day turnover is allowed
});
test('project 7: availability, booking, double booking and refunds', async () => {
const now = new Date('2026-11-10T10:00:00Z');
const app = createApp({ now: () => now });
await request(app).post('/api/rooms').set(as(1, 'admin')).send({ number: '101', type: 'double', pricePerNightCents: 300000 });
await request(app).post('/api/rooms').set(as(1, 'admin')).send({ number: '102', type: 'single', pricePerNightCents: 200000 });
const book = (user, roomId, checkIn, checkOut) => request(app).post('/api/reservations').set(as(user)).send({ roomId, checkIn, checkOut });
const first = await book(2, 1, '2026-12-20', '2026-12-23');
assert.equal(first.status, 201);
assert.equal(first.body.totalCents, 900000); // 3 nights
assert.equal((await book(3, 1, '2026-12-22', '2026-12-25')).status, 409); // overlap: refused
assert.equal((await book(3, 1, '2026-12-23', '2026-12-25')).status, 201); // starts on check-out day: allowed
const free = await request(app).get('/api/availability?checkIn=2026-12-21&checkOut=2026-12-22');
assert.deepEqual(free.body.map((r) => r.number), ['102']);
assert.equal((await request(app).get('/api/availability?checkIn=2026-12-22&checkOut=2026-12-20')).status, 422);
assert.equal((await book(4, 2, '2026-01-01', '2026-01-03')).status, 422); // in the past
const early = await request(app).post('/api/reservations/1/cancel').set(as(2));
assert.equal(early.body.refundCents, 900000); // more than 48 hours ahead: full refund
assert.equal((await book(5, 1, '2026-12-20', '2026-12-21')).status, 201); // the dates are free again
assert.equal((await request(app).post('/api/reservations/3/cancel').set(as(6))).status, 404); // not your reservation
});
test('late cancellation refunds half, failed payment frees the room', async () => {
const now = new Date('2026-11-10T10:00:00Z');
let ok = false;
const app = createApp({ now: () => now, payments: { charge: async () => ({ ok, id: 'p' }) } });
await request(app).post('/api/rooms').set(as(1, 'admin')).send({ number: '101', type: 'double', pricePerNightCents: 100000 });
const body = { roomId: 1, checkIn: '2026-11-11', checkOut: '2026-11-12' };
assert.equal((await request(app).post('/api/reservations').set(as(2)).send(body)).status, 402);
ok = true;
const booked = await request(app).post('/api/reservations').set(as(2)).send(body); // the failed attempt did not block the room
assert.equal(booked.status, 201);
const cancelled = await request(app).post(`/api/reservations/${booked.body.id}/cancel`).set(as(2));
assert.equal(cancelled.body.refundCents, 50000); // less than 48 hours: half back
});
Rules worth understanding
The overlap rule. A new stay from start to end clashes with an existing one from s to e when start < e and s < end. If end equals s, the new guest leaves exactly when the other arrives, and that is allowed. Test the boundary days explicitly.
Order of checks. Cheap checks come first, such as dates and room. The availability check comes right before the payment. In a real database, the check and the creation of the reservation must happen together, with a unique constraint or a transaction, or two requests could both pass the check at the same instant.
A failed payment is recorded. If the provider declines, the reservation is marked payment_failed and the reply is 402. The dates are not held. The reservation does not block the room.
Cancellation rule. Cancelling at least 48 hours before check-in gives a full refund, and later gives 50 percent. The rule lives in one small function that is easy to read and test, because a refund rule is exactly the sort of thing that a business will change next month.
Own reservations. A guest can cancel only their own reservation, and an admin can cancel any. Others get 404.
Security and honesty notes
Do not let the client send the price or the total. Do not accept dates in the past. Reject stays that are unreasonably long, which an attacker could use to block a room for years.
The refund percentages and the 48-hour rule here are an example and not legal advice. Real businesses must follow the consumer laws of their country and their own published terms.
Extend it
Your task
- Add a unique index or a transaction so that two simultaneous requests cannot book the same room.
- Add a temporary hold of ten minutes while the guest pays.
- Add seasonal prices, higher at weekends, calculated per night.
How to check it worked
- A stay that starts on another stay's check-out day is accepted.
- A declined payment does not block the room.
- Cancelling 10 hours before check-in refunds 50 percent.
On your resume. "Implemented a booking engine with date-range availability, overlap detection, payments and a rule-based cancellation policy, covered by boundary-case tests" is exactly the kind of line that gets questions in an interview. Write only what you really built and can explain, and keep the repository link next to it. Our resume templates have a project section that suits this, and the ATS checker shows how a tracking system reads it.