Skip to content

Controllers — The API Traffic Cops

If your NestJS app were a bustling city, controllers would be the traffic cops standing at every junction — directing incoming requests to the right destination. 🧑‍✈️

They don’t do the heavy lifting themselves, but boy do they make sure your requests get to where they need to go — services, mostly.

🧠 What’s a Controller?

A controller handles incoming requests and returns responses. That’s it. It's like the friendly receptionist who says:

"Ah, you’re here to GET /cats? Let me grab that info for you. 🐱"

🧪 The Basic Anatomy

Here’s what a classic NestJS controller looks like:

ts
import { Controller, Get } from "@nestjs/common";

@Controller("cats")
export class CatsController {
  @Get()
  findAll(): string {
    return "This action returns all cats 🐱";
  }
}

🩻 Breakdown Time:

PieceWhat It Does
@Controller('cats')Sets the base route to /cats
@Get()Listens for GET requests at /cats
findAll()Method that handles the request and sends back a response

🚀 Common Request Methods

Here are the usual suspects you’ll be using in controllers:

ts
@Get()        // Handles GET requests
@Post()       // Handles POST requests
@Put()        // Handles PUT requests
@Delete()     // Handles DELETE requests
@Patch()      // Handles PATCH requests

🧙 Magical Decorators

NestJS gives you helpful decorators to extract request data:

ts
@Get(':id')
findOne(@Param('id') id: string) {
  return `Here’s the cat with ID #${id}`;
}

@Post()
create(@Body() createCatDto: any) {
  return 'Creating a new cat...';
}
DecoratorPurpose
@Param()Grab route parameters like /cats/:id
@Body()Get JSON payload from POST/PUT requests
@Query()Access query params like /cats?age=2
@Req()Access raw request object (use with caution)

⚔️ Don't Do the Work Here!

Controllers should not be the workhorses. They're not your developers, they’re just receptionists. For real logic (like saving to a database or sending an email), call a service.

ts
constructor(private readonly catsService: CatsService) {}

@Get()
findAll() {
  return this.catsService.findAll();
}

🔄 Routing Recap

Here’s how a request flows:

User → Controller → Service → (Maybe Database) → Response

The controller only says:

“Hey Service, can you handle this? Thanks!”

🎉 Final Thoughts

NestJS controllers make your app readable, testable, and organized — and keep you from turning into a spaghetti monster 👾.

So treat them well, and don’t forget:

"Controllers direct, Services act." 💡

Built by noobs, for noobs, with love 💻❤️