Performance: Decorator-based architecture
This affects the initial server startup time and runtime metadata processing, impacting how fast the app can respond to requests.
import { Controller, Get } from '@nestjs/common'; @Controller() export class AppController { @Get() getRoot() { return 'Hello World'; } // Group related routes to reduce decorators @Get('slow') slowRoute() { // complex logic here } }
import { Controller, Get } from '@nestjs/common'; @Controller() export class AppController { @Get() getRoot() { return 'Hello World'; } @Get('slow') slowRoute() { // complex logic here } @Get('many') manyDecorators() { // many decorators stacked } }
| Pattern | Metadata Processing | Startup Time | Runtime Impact | Verdict |
|---|---|---|---|---|
| Many decorators on methods | High (many metadata entries) | Increases by 20-30% | None | [X] Bad |
| Minimal necessary decorators | Low (only essential metadata) | Minimal increase | None | [OK] Good |
@Controller() and @Injectable()?@Controller() and @Injectable() add metadata to classes, telling NestJS their purpose.@Controller() decorator is placed immediately before the class definition.@Controller() before the class. class MyController { } lacks any decorator. function Controller() { } class MyController { } incorrectly defines a function instead of using a decorator. @Injectable() class MyController { } uses @Injectable() which is for services, not controllers.@Controller('hello')
export class HelloController {
@Get()
greet() {
return 'Hello, NestJS!';
}
}@Controller('hello') sets the base path to '/hello'. The @Get() decorator on greet() means this method handles GET requests to '/hello'.greet() method returns the string 'Hello, NestJS!'. So, a GET request to '/hello' returns this string as the response.@Injectable
export class UserService {
getUser() {
return { name: 'Alice' };
}
}@Injectable decorator requires parentheses even if no arguments are passed, so it should be @Injectable().getUser() can be synchronous and return an object. Class name and return type are valid as is.@Get(':id') is correct.@Param('id') to extract the 'id' from the URL path. @Controller('users')
export class UserController {
@Get(':id')
getUser(@Param('id') id: string) {
return `User ID is ${id}`;
}
} does this correctly.@Controller('users')
export class UserController {
@Get()
getUser(@Body('id') id: string) {
return `User ID is ${id}`;
}
} uses @Body('id') which reads from request body, not URL. @Controller('users')
export class UserController {
@Post(':id')
getUser(@Param('id') id: string) {
return `User ID is ${id}`;
}
} uses POST instead of GET. @Controller('users')
export class UserController {
@Get(':id')
getUser(id: string) {
return `User ID is ${id}`;
}
} misses the @Param decorator, so 'id' won't be injected.Pass the test and this pattern moves unknown