Lesson 154 of 296
Build: in-memory store and a small REST endpoint
On this page
What the task usually looks like
"Build a small API for tasks (or products, or notes): create, list, get one, update and delete. Keep the data in memory. Validate input and return sensible status codes." Sometimes only the store (a class with methods) is required; sometimes an HTTP layer too.
This tests: data modelling, CRUD logic, validation, error handling, HTTP basics (Part 15 covers HTTP fully) and clean separation between layers.
Questions to ask first
- Which fields? Which are required? Any length limits?
- Which operations? Do we need filtering, sorting, pagination?
- What should happen for a missing item, invalid input, duplicate data?
- Framework or plain Node.js? (Express, NestJS or Node's built-in
httpmodule.)
Layer 1: the store
Keep business logic separate from HTTP. Then the store can be tested without starting a server, and could be swapped for a database later.
type Task = {
id: string;
title: string;
done: boolean;
createdAt: string;
};
type NewTask = { title: string };
type TaskChanges = Partial<Pick<Task, "title" | "done">>;
class NotFoundError extends Error {
constructor(resource: string, id: string) {
super(`${resource} ${id} not found`);
this.name = "NotFoundError";
}
}
class ValidationError extends Error {
constructor(message: string) {
super(message);
this.name = "ValidationError";
}
}
class TaskStore {
private tasks = new Map<string, Task>();
private nextId = 1;
create(input: NewTask): Task {
const title = this.validateTitle(input.title);
const task: Task = {
id: String(this.nextId++),
title,
done: false,
createdAt: new Date().toISOString()
};
this.tasks.set(task.id, task);
return task;
}
get(id: string): Task {
const task = this.tasks.get(id);
if (!task) throw new NotFoundError("Task", id);
return task;
}
list(options: { done?: boolean; limit?: number; offset?: number } = {}): {
items: Task[];
total: number;
} {
const { done, limit = 20, offset = 0 } = options;
let items = [...this.tasks.values()];
if (done !== undefined) items = items.filter((t) => t.done === done);
return { items: items.slice(offset, offset + limit), total: items.length };
}
update(id: string, changes: TaskChanges): Task {
const task = this.get(id);
const updated: Task = {
...task,
...(changes.title !== undefined ? { title: this.validateTitle(changes.title) } : {}),
...(changes.done !== undefined ? { done: changes.done } : {})
};
this.tasks.set(id, updated);
return updated;
}
delete(id: string): void {
if (!this.tasks.delete(id)) throw new NotFoundError("Task", id);
}
private validateTitle(title: unknown): string {
if (typeof title !== "string") throw new ValidationError("title must be a string");
const trimmed = title.trim();
if (trimmed.length === 0) throw new ValidationError("title is required");
if (trimmed.length > 200) throw new ValidationError("title must be 200 characters or fewer");
return trimmed;
}
}Design points to mention:
- A Map gives O(1) get, update and delete by ID.
- Custom errors (Lesson 72) let the HTTP layer choose status codes without the store knowing about HTTP.
updatecreates a new object instead of mutating, and only accepts the fields allowed to change (TaskChanges), so a client cannot overwriteidorcreatedAt.listsupports filtering and pagination (limit and offset) and returns thetotal, so a front end can show page numbers.- Real IDs would usually be UUIDs (
crypto.randomUUID()); a counter keeps the example readable.
Layer 2: HTTP
A minimal endpoint using Node.js's built-in http module (in a real project you would likely use Express, Fastify or NestJS, Part 16):
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
function sendJson(res: ServerResponse, status: number, body: unknown): void {
res.writeHead(status, { "Content-Type": "application/json" });
res.end(body === undefined ? undefined : JSON.stringify(body));
}
async function readJson(req: IncomingMessage): Promise<unknown> {
const chunks: Buffer[] = [];
let size = 0;
for await (const chunk of req) {
size += (chunk as Buffer).length;
if (size > 1_000_000) throw new ValidationError("body too large");
chunks.push(chunk as Buffer);
}
if (chunks.length === 0) return {};
try {
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
} catch {
throw new ValidationError("body must be valid JSON");
}
}
function createTaskServer(store: TaskStore) {
return createServer(async (req, res) => {
try {
const url = new URL(req.url ?? "/", "http://localhost");
const match = url.pathname.match(/^\/tasks(?:\/([^/]+))?$/);
if (!match) return sendJson(res, 404, { error: "Route not found" });
const id = match[1];
if (req.method === "GET" && !id) {
const doneParam = url.searchParams.get("done");
return sendJson(res, 200, store.list({
done: doneParam === null ? undefined : doneParam === "true",
limit: Number(url.searchParams.get("limit") ?? 20),
offset: Number(url.searchParams.get("offset") ?? 0)
}));
}
if (req.method === "POST" && !id) {
const body = (await readJson(req)) as { title?: unknown };
return sendJson(res, 201, store.create({ title: body.title as string }));
}
if (req.method === "GET" && id) return sendJson(res, 200, store.get(id));
if (req.method === "PATCH" && id) {
const body = (await readJson(req)) as TaskChanges;
return sendJson(res, 200, store.update(id, body));
}
if (req.method === "DELETE" && id) {
store.delete(id);
res.writeHead(204);
return res.end();
}
return sendJson(res, 405, { error: "Method not allowed" });
} catch (error) {
if (error instanceof ValidationError) return sendJson(res, 400, { error: error.message });
if (error instanceof NotFoundError) return sendJson(res, 404, { error: error.message });
console.error(error);
return sendJson(res, 500, { error: "Internal server error" });
}
});
}The routes
| Method and path | Action | Success status |
|---|---|---|
GET /tasks?done=true&limit=20&offset=0 | List with filter and pagination | 200 |
POST /tasks | Create | 201 Created |
GET /tasks/:id | Get one | 200 |
PATCH /tasks/:id | Partly update | 200 |
DELETE /tasks/:id | Delete | 204 No Content |
| Error | Status |
|---|---|
| Invalid input or invalid JSON | 400 Bad Request |
| Task or route not found | 404 Not Found |
| Wrong method on a route | 405 Method Not Allowed |
| Unexpected error | 500, with a generic message; details only in the log |
Points that impress interviewers
- Errors are mapped in one place (the
catch), not scattered through every route. - Never leak internal error details to the client (Part 20).
- The body size is limited, so a huge request cannot exhaust memory.
- The handler is thin: it parses the request, calls the store, and formats the response. Logic lives in the store.
- What you would add: schema validation with Zod, authentication, rate limiting (Lesson 155), logging, persistence in PostgreSQL (Part 17), and integration tests with Supertest (Part 15).
How to say it in an interview
"I separate the store, which holds the business logic in a Map with validation and custom errors, from a thin HTTP layer that parses requests, calls the store and maps errors to status codes in one place: 400 for validation, 404 for missing items, 500 with a generic message for anything unexpected. Create returns 201 and delete 204. Updates only accept allowed fields and return a new object. Listing supports filtering and limit and offset pagination with a total. Next I'd add schema validation, auth, persistence and integration tests."
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.