Skip to content
NestPath

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)

  1. What are the two array properties you registered in @Module({...}) for the tasks feature, and what belongs in each?
  2. Why does NestJS use classes for DTOs but interfaces for internal models like Task? What is the runtime difference?
  3. In one sentence each, what is the responsibility of a Controller vs a Service? What's the "5 lines" rule of thumb?
  4. Write the full request lifecycle from memory, in order (there are 9 stages from request to response). Which component runs twice?
  5. You never write new TasksService() anywhere. Who instantiates it, when, and how many instances exist by default?
  6. Why is ParseIntPipe needed on @Param('id')? Is it validation or transformation? What bug occurs without it?
  7. What happens right now (before validation is added) if a client POSTs { "garbage": true } to /tasks? Trace the value of createTaskDto.title in the service.
  8. 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?
  9. What does constructor(private readonly tasksService: TasksService) {} actually do — list the 3 things TypeScript + NestJS accomplish in that single line.
  10. What does nest g resource tasks generate, 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)

  1. nest new practice-api, delete the default app.controller.ts / app.service.ts (and remove them from AppModule).
  2. Generate a tasks module, controller, and service with the CLI.
  3. Create interfaces/task.interface.ts and both DTOs by hand.
  4. Implement all 5 service methods: findAll, findOne, create, update, remove — in-memory array, incrementing id counter, NotFoundException on missing ids.
  5. 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:

json
{ "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/completed removes 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

ts
@Module({
  controllers: [TasksController, TasksService],
})
export class TasksModule {}

Symptom: Nest can't resolve dependencies of the TasksController.

D2

ts
@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

ts
@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

ts
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

ts
@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:

  1. GET /task (singular) — what does NestJS return?
  2. POST /tasks with body { "title": "x", "description": "y", "id": 999 } — what id does the created task have, and why?
  3. PATCH /tasks/2 with body {} — what happens?
  4. DELETE /tasks/abc — status code and who produced the error?
  5. Controller method throws throw new Error('boom') (plain Error, not HttpException) — what does the client see?

Part F — Stretch Goals

  1. Add createdAt/updatedAt to tasks; updatedAt refreshes on every update — done inside the service, controller untouched.
  2. Implement soft-delete: DELETE sets deletedAt instead of splicing; findAll hides soft-deleted tasks; add GET /tasks/trash and PATCH /tasks/:id/restore.
  3. Read about provider scopes (Scope.DEFAULT vs Scope.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/imports and 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.