正在加载,请稍候…

NestJS: Building Scalable Node.js APIs with Dependency Injection

Build production APIs with NestJS — modules, dependency injection, guards, interceptors, pipes, custom decorators, and TypeORM.

NestJS Architecture

Controllers handle HTTP. Services handle business logic. Modules organize everything.

Controller + Service + DI

@Controller('users')
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Get()
  @UseGuards(JwtAuthGuard)
  findAll() { return this.usersService.findAll() }

  @Post()
  @HttpCode(HttpStatus.CREATED)
  create(@Body() dto: CreateUserDto) { return this.usersService.create(dto) }

  @Get(':id')
  findOne(@Param('id', ParseIntPipe) id: number) { return this.usersService.findOne(id) }

  @Delete(':id')
  @UseGuards(JwtAuthGuard)
  remove(@Param('id', ParseIntPipe) id: number, @CurrentUser() user: User) {
    return this.usersService.remove(id, user.id)
  }
}

DTO Validation

import { IsEmail, IsString, MinLength } from 'class-validator'
import { Transform } from 'class-transformer'

export class CreateUserDto {
  @IsEmail()
  @Transform(({ value }) => value.toLowerCase())
  email: string

  @IsString()
  @MinLength(8)
  password: string
}

// main.ts: global validation
app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true, forbidNonWhitelisted: true }))

Custom Decorator

export const CurrentUser = createParamDecorator(
  (field: string, ctx: ExecutionContext) => {
    const req = ctx.switchToHttp().getRequest()
    return field ? req.user?.[field] : req.user
  }
)

Response Interceptor

@Injectable()
export class ResponseInterceptor implements NestInterceptor {
  intercept(ctx: ExecutionContext, next: CallHandler) {
    return next.handle().pipe(
      map(data => ({ success: true, data, timestamp: new Date().toISOString() }))
    )
  }
}

-> Format API responses with the JSON Viewer.