Exercises — Basic CRUD & Architecture
Covers: Modules, Controllers, Services, Dependency Injection, DTOs vs Interfaces, the complete request lifecycle, ParseIntPipe, CLI usage.
Part A — Concept Checks (closed book)
- What are the two array properties you registered in
@Module({...})for the tasks feature, and what belongs in each? - Why does NestJS use classes for DTOs but interfaces for internal models like
Task? What is the runtime difference? - In one sentence each, what is the responsibility of a Controller vs a Service? What's the "5 lines" rule of thumb?
- Write the full request lifecycle from memory, in order (there are 9 stages from request to response). Which component runs twice?
- You never write
new TasksService()anywhere. Who instantiates it, when, and how many instances exist by default? - Why is
ParseIntPipeneeded on@Param('id')? Is it validation or transformation? What bug occurs without it? - What happens right now (before validation is added) if a client POSTs
{ "garbage": true }to/tasks? Trace the value ofcreateTaskDto.titlein the service. - Which decorator extracts the request body? Which extracts a URL parameter? Which HTTP decorator would you use for a partial update and why not
@Put? - What does
constructor(private readonly tasksService: TasksService) {}actually do — list the 3 things TypeScript + NestJS accomplish in that single line. - What does
nest g resource tasksgenerate, and what two folders from the lesson's structure do you still create manually?
Part B — Guided Exercises
B1. Rebuild Tasks from scratch (no peeking until stuck)
nest new practice-api, delete the defaultapp.controller.ts/app.service.ts(and remove them fromAppModule).- Generate a
tasksmodule, controller, and service with the CLI. - Create
interfaces/task.interface.tsand both DTOs by hand. - Implement all 5 service methods:
findAll,findOne,create,update,remove— in-memory array, incrementing id counter,NotFoundExceptionon missing ids. - Implement all 5 controller routes with correct decorators and
ParseIntPipe.
Checkpoint: All of these must behave exactly as stated: - POST /tasks → 201 with the new task - GET /tasks → 200 with array - GET /tasks/1 → 200 with one task; GET /tasks/999 → 404 - PATCH /tasks/1 with { "done": true } → only done changes - DELETE /tasks/1 → 200; then GET /tasks/1 → 404
B2. Add a second resource: notes
Same shape of work, different domain — this is deliberate repetition. - Note = { id, text, pinned, createdAt } - Full CRUD + one extra endpoint: PATCH /notes/:id/pin that toggles pinned. - Wire NotesModule into AppModule yourself (don't rely on CLI auto-wiring — delete the import and re-add it manually so you feel what the CLI does).
B3. Cross-service injection
Create a StatsModule with a GET /stats endpoint returning:
{ "totalTasks": 4, "completedTasks": 1, "totalNotes": 2, "pinnedNotes": 1 }Rules: - StatsService must inject TasksService and NotesService — no duplicated arrays. - You will hit a DI error: Nest can't resolve dependencies of the StatsService. Fix it properly using exports in TasksModule/NotesModule and imports in StatsModule. Understand why the error happened before fixing it.
Part C — Independent Challenges (requirements only)
C1. Query filtering
GET /tasks?done=true returns only completed tasks; GET /tasks?search=nest returns tasks whose title or description contains "nest" (case-insensitive). Both filters combinable. Hint: @Query() decorator — you haven't seen it in the lesson; go find it in the NestJS docs. Learning to read docs is part of the exercise.
C2. Business rules in the service
- Reject creating a task whose title duplicates an existing task (case-insensitive) → throw
ConflictException(409). DELETE /tasks/completedremoves all done tasks and returns{ "removed": <count> }. Careful: route ordering matters — if@Delete(':id')is declared before@Delete('completed'), what happens and why?
C3. Priority sub-resource
Add priority: 'low' | 'medium' | 'high' to tasks (default 'medium'), plus GET /tasks/priority/:level returning tasks of that priority, 400 on invalid level (manual check in the service for now — you'll replace this with validation in Module 02).
Part D — Debug Drills
Each snippet has at least one bug. Find it, explain it, fix it.
D1
@Module({
controllers: [TasksController, TasksService],
})
export class TasksModule {}Symptom: Nest can't resolve dependencies of the TasksController.
D2
@Get(':id')
findOne(@Param('id') id: number): Task {
return this.tasksService.findOne(id);
}Symptom: GET /tasks/1 always returns 404 even though task 1 exists.
D3
@Controller('tasks')
export class TasksController {
private tasksService = new TasksService();
// routes...
}Compiles and even works. Why is this still wrong? Name two concrete problems it causes later.
D4
update(id: number, dto: UpdateTaskDto): Task {
const task = this.findOne(id);
task = { ...task, ...dto }; // ← something wrong here, and something subtler too
return task;
}Symptom: compiler error, and even after "fixing" the compile error, GET /tasks/:id shows the task unchanged. Explain both issues (hint: reference vs reassignment).
D5
@Post()
create(@Body() dto: CreateTaskDto): Task {
const task = this.tasksService.create(dto);
return task.id; // returns just the id number
}Not a crash — a design smell. What contract are you breaking and how would a frontend suffer?
Part E — Prediction Drills
Without running code, write down the exact status code + body:
GET /task(singular) — what does NestJS return?POST /taskswith body{ "title": "x", "description": "y", "id": 999 }— what id does the created task have, and why?PATCH /tasks/2with body{}— what happens?DELETE /tasks/abc— status code and who produced the error?- Controller method throws
throw new Error('boom')(plain Error, not HttpException) — what does the client see?
Part F — Stretch Goals
- Add
createdAt/updatedAtto tasks;updatedAtrefreshes on every update — done inside the service, controller untouched. - Implement soft-delete:
DELETEsetsdeletedAtinstead of splicing;findAllhides soft-deleted tasks; addGET /tasks/trashandPATCH /tasks/:id/restore. - Read about provider scopes (
Scope.DEFAULTvsScope.REQUEST) and write a 5-line summary of when a request-scoped service makes sense.
Self-Assessment Checklist
- I can scaffold module + controller + service from memory (CLI or by hand)
- I can explain why DTOs are classes and models are interfaces
- I can list the 9 lifecycle stages in order without notes
- I can wire cross-module DI with
exports/importsand explain the resolution error - I know why controllers stay thin and where business logic belongs
- My CRUD passes every checkpoint in B1 verified via real HTTP calls
Answers & Hints
A1: controllers: [TasksController], providers: [TasksService]. Controllers handle routes; providers are injectable classes (services, and later filters/guards registered via tokens).
A2: Interfaces are erased at compile time — no runtime existence, so nothing to attach validation decorator metadata to. Classes exist at runtime, so class-validator decorators can be read later. Internal models never need runtime metadata → interfaces are fine.
A3: Controller: map HTTP → method call, extract params/body, return result. Service: all business logic and data access. If a controller method exceeds ~5 lines of logic, logic is leaking into the wrong layer.
A4: Middleware → Guards → Interceptors (pre) → Pipes → Controller → Service → Controller returns → Interceptors (post) → Exception Filters (on error). Interceptors run twice.
A5: The NestJS DI container, at application bootstrap, one singleton per provider by default, shared everywhere it's injected.
A6: URL params are always strings. Transformation, not validation. Without it, id === "1" and find(t => t.id === 1) never matches with === → false 404s.
A7: No runtime validation exists yet, so the body reaches the service as-is: title and description are undefined; a task with undefined fields is created. DTOs are "decorative" until ValidationPipe.
A8: @Body(), @Param('name'). @Patch for partial updates — PUT semantically replaces the whole resource; PATCH modifies a subset.
A9: (1) declares a constructor parameter typed TasksService, (2) TS parameter-property shorthand creates+assigns this.tasksService, (3) NestJS reads the type metadata and injects the singleton from the module's providers.
A10: Module, controller, service, DTO stubs, entity stub, and spec files — plus it auto-adds the module to AppModule imports. You still create interfaces/ (and in the lesson's flow, shape the dto/ files) yourself.
D1: TasksService is in controllers instead of providers. The DI container never registers it as a provider, so injection fails.
D2: Missing ParseIntPipe. id is a string at runtime despite the number annotation; strict comparison in the service fails.
D3: Bypasses DI. Problems: (1) can't mock/replace the service in tests, (2) breaks the singleton — this controller has a private copy of the tasks array, so any other consumer of TasksService sees different data; (3) if TasksService later gains constructor dependencies, new TasksService() breaks.
D4: task is const-like binding of a parameter? No — the real issues: reassigning task = {...} creates a new object; the array still holds the old one, so the store never changes. Fix: Object.assign(task, dto) mutates the object the array references (or replace the element in the array by index). The compile error appears if task was declared const.
D5: The endpoint's response contract becomes inconsistent (POST returns a bare number while GET returns objects). Frontend must special-case; also loses the created resource data, forcing an extra GET.
E1: 404 {"statusCode":404,"message":"Cannot GET /task","error":"Not Found"} — route not matched.
E2: The extra id is currently not stripped (no whitelist yet) but the service ignores it — it builds the task using idCounter++, so the id is server-assigned. (After Module 02 with forbidNonWhitelisted, this request would 400.)
E3: 200; Object.assign(task, {}) changes nothing; the unchanged task is returned.
E4: 400 from ParseIntPipe: "Validation failed (numeric string is expected)".
E5: 500 {"statusCode":500,"message":"Internal server error"} — NestJS's default handler masks non-HttpExceptions.
C2 route-order hint: NestJS matches routes in declaration order; ':id' would swallow 'completed' and ParseIntPipe would 400 on "completed". Declare static segments before parameterized ones.
