Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 42 ยท Practice and Review

Exercises: Core Concepts

Practice NestJS core concepts with six exercises on controllers, dependency injection, modules, pipes, guards and pipeline order, each with a full solution.

Reading about NestJS is not the same as writing it. This page gives you six exercises that cover the core ideas from the first chapters: controllers and routing, providers and dependency injection, modules, pipes and guards.

Try each exercise on paper or in your own Nest project before opening the solution. Each solution has two parts. The Nest code is read-only, because it needs Node and npm. Next to it is a runnable stand-in in plain JavaScript that reproduces the behavior (it is not Nest's real implementation), so you can check your reasoning by running code in the browser.

How to use this page

Attempt first Write your answer before you look.
Run the stand-in See the behavior in the editor.
Compare Read the Nest version and find the differences.

Being wrong and then fixing it teaches more than reading a solution.

1 / 2

Exercise 1: a cats controller

Task. Build a CatsController mounted at /cats with three routes:

  • GET /cats returns every cat and supports ?limit=2.
  • GET /cats/:id returns one cat, answers 400 when id is not a number and 404 when no cat has that id.
  • POST /cats creates a cat from a body with a name and answers 201.

Hint. Use ParseIntPipe for the id and throw NotFoundException from the service.

Solution (Nest, read-only)
TypeScript
@Controller('cats')
export class CatsController {
  constructor(private readonly cats: CatsService) {}

  @Get()
  findAll(@Query('limit') limit?: string) {
    return this.cats.findAll(limit ? Number(limit) : undefined);
  }

  @Get(':id')
  findOne(@Param('id', ParseIntPipe) id: number) {
    return this.cats.findOne(id); // throws NotFoundException when missing
  }

  @Post()
  create(@Body() dto: CreateCatDto) {
    return this.cats.create(dto); // POST answers 201 by default
  }
}

The next stand-in is not Nest. It is a tiny route table and dispatcher with :param segments, a numeric-string check that behaves like ParseIntPipe, and a repository that throws a 404. It covers exercises 1 to 3 together.

Exercise 2: dependency injection and a test double

Task. CatsService needs a CatsRepository. Write both as providers, then replace the repository with a fake for a test, without changing CatsService.

Solution (Nest, read-only)
TypeScript
@Injectable()
export class CatsRepository {
  private cats = [{ id: 1, name: 'Tom' }];
  findAll() { return this.cats; }
  findOne(id: number) { return this.cats.find((c) => c.id === id); }
}

@Injectable()
export class CatsService {
  constructor(private readonly repo: CatsRepository) {}

  findOne(id: number) {
    const cat = this.repo.findOne(id);
    if (!cat) throw new NotFoundException(`Cat ${id} not found`);
    return cat;
  }
}

// in a test
const moduleRef = await Test.createTestingModule({
  providers: [CatsService, { provide: CatsRepository, useValue: fakeRepo }],
}).compile();

The key point: CatsService only asks for CatsRepository in its constructor. It never creates one, so the container can hand it any object with the same methods.

Exercise 3: module visibility

Task. AdminModule has a controller that needs CatsService. CatsModule owns CatsService. Make the injection work, then explain why it fails if you forget one line.

Solution (Nest, read-only)
TypeScript
@Module({
  controllers: [CatsController],
  providers: [CatsService, CatsRepository],
  exports: [CatsService],            // line 1: make it public
})
export class CatsModule {}

@Module({
  imports: [CatsModule],             // line 2: use the public API
  controllers: [AdminController],
})
export class AdminModule {}

Providers are private to their module. Without exports on CatsModule, or without imports on AdminModule, Nest fails at startup with an error saying it cannot resolve the dependency of AdminController. Note that CatsRepository stays hidden: it is not exported, so no other module can inject it.

JS Exercises 1-3: router, DI container and module visibility

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The two lookups at the end mirror Nest's rule: a module may use its own providers and whatever its imported modules export. AdminModule reaches CatsService because it is exported, but not CatsRepository, which stays private.

Exercise 4: write a custom pipe

Task. Query strings are text. Write a ClampPipe that turns ?limit= into a number, uses a default when the value is missing, rejects non-numbers with 400, and keeps the result between a minimum and a maximum.

Solution (Nest, read-only)
TypeScript
@Injectable()
export class ClampPipe implements PipeTransform<string | undefined, number> {
  constructor(
    private readonly min: number,
    private readonly max: number,
    private readonly fallback: number,
  ) {}

  transform(value: string | undefined): number {
    if (value === undefined || value === '') return this.fallback;
    const n = Number(value);
    if (!Number.isInteger(n)) {
      throw new BadRequestException('limit must be an integer');
    }
    return Math.min(this.max, Math.max(this.min, n));
  }
}

@Get()
findAll(@Query('limit', new ClampPipe(1, 50, 10)) limit: number) { /* ... */ }

Exercise 5: an API key guard

Task. Protect the admin routes with an x-api-key header. A missing header answers 401. A key that is not on the allowed list answers 403. A valid key lets the request through.

Solution (Nest, read-only)
TypeScript
@Injectable()
export class ApiKeyGuard implements CanActivate {
  constructor(private readonly config: ConfigService) {}

  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    const key = request.headers['x-api-key'];
    if (!key) throw new UnauthorizedException();
    const allowed = this.config.getOrThrow<string>('API_KEYS').split(',');
    return allowed.includes(key); // false becomes 403
  }
}

Notice the two different failures: throwing gives you control of the status (401, "who are you?"), while returning false produces the default 403 ("I know what you sent, the answer is no").

Exercise 6: predict the order

Task. A route has a global middleware, a guard, an interceptor and a pipe, and the handler throws. In which order do they run, and which of them see the error? Write your answer first.

Solution

Middleware, then guard, then the interceptor's "before" part, then the pipe, then the handler. The handler throws, so the interceptor's "after" part sees the error (it can catch or transform it), and finally the exception filter turns what is left into a response. Pipes run after interceptors, which surprises many people.

The stand-in below runs exercises 4 and 5 and then prints the order for exercise 6, using a hand-built chain (not Nest's engine).

JS Exercises 4-6: clamp pipe, API key guard and pipeline order

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Run it and compare the last two lines with your prediction. The order is fixed by Nest, and the stand-in prints it by hand, so treat it as a memory aid and check the real order in Interceptors and Guards.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Module B imports module A and wants to inject A's CatsService, but Nest refuses to start. What is the most likely missing piece?

    Providers are private unless the owning module exports them. Importing the module is not enough on its own.
  2. 2. A guard returns false. A second guard throws UnauthorizedException. What status codes do the two produce?

    A plain false becomes ForbiddenException (403). Throwing lets you pick the status, here 401.
  3. 3. GET /cats/abc goes through @Param('id', ParseIntPipe). What does the client receive?

    ParseIntPipe throws a BadRequestException when the value is not a numeric string.
  4. 4. Why can a test replace CatsRepository without editing CatsService?

    That is the point of constructor injection: the class declares what it needs and never decides where it comes from.
  5. 5. In the request pipeline, which runs first?

    The order is middleware, guards, interceptors, pipes, handler. Exception filters only run when something throws.

Summary

  • Controllers map routes to methods; pipes such as ParseIntPipe turn text into typed values and reject bad input with 400.
  • Providers receive their dependencies through the constructor, which is what makes test doubles easy.
  • A module's providers are private until exported, and other modules must import it to use them.
  • Guards decide yes or no: false is a 403, a thrown exception chooses its own status.
  • The pipeline order is middleware, guards, interceptors, pipes, handler, with exception filters catching errors.

Ready for harder ground? Continue with Exercises: Advanced Patterns.