Your readJson() helper now refuses a body with the wrong Content-Type, a body that’s too big, and a body that isn’t JSON. Zoë Martin’s entry gets past all three checks, yet the board still answers her with the placeholder 404. Mrs. Okafor’s waiting list is as empty as it was this morning.
In this lesson, you’ll finish POST /waitlist. You’ll check that the data really is an entry, add it to a file with one line of code, and answer with the status that says it worked. The readJson() helper leaves one gap open on purpose. It accepts valid JSON that isn’t a waiting list entry, so start there.
Check the Entry’s Fields
At the end of Parse the Body With a readJson() Helper, the body "Zoë Martin" parsed without complaint because a lone string is valid JSON. Whatever parses reaches the handler as body.data. Its type is unknown, so the handler can’t read a name from it yet.
Create waitlist.ts next to server.ts, with a type for an entry and a function that turns unknown data into one:
waitlist.ts
import { appendFile } from "node:fs/promises";
export type Entry = {
name: string;
contact: string;
};
export function toEntry(data: unknown): Entry | undefined {
if (typeof data !== "object" || data === null) {
return undefined;
}
if (!("name" in data) || !("contact" in data)) {
return undefined;
}
const { name, contact } = data;
if (
typeof name !== "string" ||
typeof contact !== "string"
) {
return undefined;
}
return { name, contact };
}
The toEntry() function narrows unknown with the typeof and in checks you know from TypeScript and returns undefined unless the data is an object with a string name and a string contact.
It builds a new object from those two fields, so anything else a client sends never reaches the file.
These checks are only a stand-in. They let an empty name through, and every new field needs another typeof. A schema library handles validation later on the path.
When toEntry() returns undefined, which status fits? The body was valid JSON, so its syntax isn’t the problem. This board follows one rule for every body. It answers 400 Bad Request for a body that isn’t valid JSON and 422 Unprocessable Content for valid JSON that breaks the endpoint’s rules. The status alone tells the client whether to fix the syntax or the fields.