--- name: nestjs description: NestJS modular architecture patterns including modules, services, controllers, DTOs, and database integration. Use for building scalable Node.js backend applications with Prisma ORM. --- # NestJS Modular Architecture > Scalable backend development with NestJS. ## Instructions ### 1. Module Structure ``` src/ ├── main.ts ├── app.module.ts ├── common/ │ ├── decorators/ │ ├── filters/ │ ├── guards/ │ └── interceptors/ └── modules/ └── users/ ├── users.module.ts ├── users.controller.ts ├── users.service.ts ├── dto/ │ ├── create-user.dto.ts │ └── update-user.dto.ts └── entities/ └── user.entity.ts ``` ### 2. Module ```typescript // users/users.module.ts import { Module } from '@nestjs/common'; import { UsersController } from './users.controller'; import { UsersService } from './users.service'; @Module({ controllers: [UsersController], providers: [UsersService], exports: [UsersService], }) export class UsersModule {} ``` ### 3. Controller ```typescript // users/users.controller.ts @Controller('users') export class UsersController { constructor(private readonly usersService: UsersService) {} @Get() findAll(): Promise { return this.usersService.findAll(); } @Get(':id') findOne(@Param('id') id: string): Promise { return this.usersService.findOne(id); } @Post() create(@Body() createUserDto: CreateUserDto): Promise { return this.usersService.create(createUserDto); } @Patch(':id') update( @Param('id') id: string, @Body() updateUserDto: UpdateUserDto, ): Promise { return this.usersService.update(id, updateUserDto); } @Delete(':id') remove(@Param('id') id: string): Promise { return this.usersService.remove(id); } } ``` ### 4. Service ```typescript // users/users.service.ts @Injectable() export class UsersService { constructor(private prisma: PrismaService) {} async findAll(): Promise { return this.prisma.user.findMany(); } async findOne(id: string): Promise { const user = await this.prisma.user.findUnique({ where: { id } }); if (!user) throw new NotFoundException('User not found'); return user; } async create(dto: CreateUserDto): Promise { return this.prisma.user.create({ data: dto }); } async update(id: string, dto: UpdateUserDto): Promise { await this.findOne(id); // Check exists return this.prisma.user.update({ where: { id }, data: dto }); } async remove(id: string): Promise { await this.findOne(id); await this.prisma.user.delete({ where: { id } }); } } ``` ### 5. DTOs with Validation ```typescript // users/dto/create-user.dto.ts import { IsEmail, IsString, MinLength } from 'class-validator'; export class CreateUserDto { @IsString() @MinLength(2) name: string; @IsEmail() email: string; @IsString() @MinLength(8) password: string; } // users/dto/update-user.dto.ts import { PartialType } from '@nestjs/mapped-types'; export class UpdateUserDto extends PartialType(CreateUserDto) {} ``` ### 6. Exception Handling ```typescript // common/filters/http-exception.filter.ts @Catch(HttpException) export class HttpExceptionFilter implements ExceptionFilter { catch(exception: HttpException, host: ArgumentsHost) { const ctx = host.switchToHttp(); const response = ctx.getResponse(); const status = exception.getStatus(); response.status(status).json({ success: false, statusCode: status, message: exception.message, timestamp: new Date().toISOString(), }); } } ``` ### 7. Guards ```typescript // common/guards/auth.guard.ts @Injectable() export class AuthGuard implements CanActivate { constructor(private jwtService: JwtService) {} async canActivate(context: ExecutionContext): Promise { const request = context.switchToHttp().getRequest(); const token = this.extractToken(request); if (!token) throw new UnauthorizedException(); try { const payload = await this.jwtService.verify(token); request.user = payload; return true; } catch { throw new UnauthorizedException(); } } } ``` ## References - [NestJS Documentation](https://docs.nestjs.com/) - [Prisma with NestJS](https://docs.nestjs.com/recipes/prisma)