home / skills / doanchienthangdev / omgkit / nestjs

This skill helps you build scalable NestJS backends with TypeORM, DI, and microservices patterns for REST/GraphQL APIs.

npx playbooks add skill doanchienthangdev/omgkit --skill nestjs

Review the files below or copy the command above to add this skill to your agents.

Files (1)
SKILL.md
4.0 KB
---
name: building-nestjs-apis
description: Builds enterprise NestJS applications with TypeScript, dependency injection, TypeORM, and microservices patterns. Use when creating scalable Node.js backends, REST/GraphQL APIs, or microservices.
---

# NestJS

## Quick Start

```typescript
import { Controller, Get, Module, NestFactory } from '@nestjs/common';

@Controller('health')
class HealthController {
  @Get()
  check() {
    return { status: 'ok' };
  }
}

@Module({ controllers: [HealthController] })
class AppModule {}

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();
```

## Features

| Feature | Description | Guide |
|---------|-------------|-------|
| Modules | Dependency injection, providers | [MODULES.md](MODULES.md) |
| Controllers | Routes, validation, guards | [CONTROLLERS.md](CONTROLLERS.md) |
| Services | Business logic, repositories | [SERVICES.md](SERVICES.md) |
| Database | TypeORM, Prisma integration | [DATABASE.md](DATABASE.md) |
| Auth | Passport, JWT, guards | [AUTH.md](AUTH.md) |
| Testing | Unit, e2e with Jest | [TESTING.md](TESTING.md) |

## Common Patterns

### Controller with Validation

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

  @Get()
  @Roles('admin')
  findAll(@Query() query: PaginationDto) {
    return this.usersService.findAll(query);
  }

  @Get(':id')
  findOne(@Param('id', ParseUUIDPipe) id: string) {
    return this.usersService.findOne(id);
  }

  @Post()
  create(@Body() dto: CreateUserDto) {
    return this.usersService.create(dto);
  }
}
```

### Service with Repository

```typescript
@Injectable()
export class UsersService {
  constructor(private readonly usersRepo: UsersRepository) {}

  async findAll(query: PaginationDto) {
    const [users, total] = await this.usersRepo.findAllWithCount({
      skip: query.skip,
      take: query.limit,
    });
    return { data: users, total, page: query.page };
  }

  async findOne(id: string) {
    const user = await this.usersRepo.findOne({ where: { id } });
    if (!user) throw new NotFoundException('User not found');
    return user;
  }

  async create(dto: CreateUserDto) {
    const exists = await this.usersRepo.findByEmail(dto.email);
    if (exists) throw new ConflictException('Email in use');
    return this.usersRepo.save(this.usersRepo.create(dto));
  }
}
```

### DTO with Validation

```typescript
export class CreateUserDto {
  @IsEmail()
  email: string;

  @IsString()
  @MinLength(2)
  name: string;

  @IsString()
  @MinLength(8)
  @Matches(/^(?=.*[A-Z])(?=.*\d)/, {
    message: 'Password must contain uppercase and number',
  })
  password: string;

  @IsOptional()
  @IsEnum(UserRole)
  role?: UserRole;
}
```

## Workflows

### API Development

1. Create module with `nest g module [name]`
2. Create controller and service
3. Define DTOs with class-validator
4. Add guards for auth/roles
5. Write unit and e2e tests

### Module Structure

```typescript
@Module({
  imports: [TypeOrmModule.forFeature([User])],
  controllers: [UsersController],
  providers: [UsersService, UsersRepository],
  exports: [UsersService],
})
export class UsersModule {}
```

## Best Practices

| Do | Avoid |
|----|-------|
| Use dependency injection | Direct instantiation |
| Validate with DTOs | Trusting input |
| Use guards for auth | Auth logic in controllers |
| Use interceptors for cross-cutting | Duplicating logging/transform |
| Write unit + e2e tests | Skipping test coverage |

## Project Structure

```
src/
├── main.ts
├── app.module.ts
├── common/
│   ├── decorators/
│   ├── guards/
│   ├── interceptors/
│   └── pipes/
├── config/
├── users/
│   ├── users.module.ts
│   ├── users.controller.ts
│   ├── users.service.ts
│   ├── dto/
│   └── entities/
└── auth/
    ├── auth.module.ts
    ├── strategies/
    └── guards/
```

For detailed examples and patterns, see reference files above.

Overview

This skill builds enterprise-grade NestJS applications using TypeScript, dependency injection, TypeORM (or Prisma) and microservice patterns. It scaffolds modules, controllers, services, DTOs, and common cross-cutting concerns to create scalable REST or GraphQL backends and microservices. The kit emphasizes testability, validation, and clean module boundaries.

How this skill works

It generates a modular project layout and provides example controllers, services, repositories, and DTOs wired with NestJS dependency injection. It configures database integration with TypeORM (or Prisma), authentication guards (Passport/JWT), and common pipes/interceptors. It includes patterns for validation, error handling, and testing so you can plug in business logic and microservice transports quickly.

When to use it

  • Building a new scalable Node.js backend with NestJS and TypeScript
  • Creating REST or GraphQL APIs with typed DTO validation and role-based guards
  • Designing microservices or service meshes with NestJS transport strategies
  • Integrating relational databases via TypeORM or switching to Prisma
  • Enforcing test-driven development with unit and end-to-end tests

Best practices

  • Organize code into feature modules to keep boundaries clean and enable reusability
  • Use DTOs with class-validator for input validation and clear API contracts
  • Keep controllers thin: move business logic to services and repositories
  • Apply guards and interceptors for authentication, authorization, and cross-cutting concerns
  • Write unit tests for services and e2e tests for API contracts before deploying

Example use cases

  • User management microservice with role-based access and pagination endpoints
  • Monolith-to-microservice split where each domain becomes a NestJS module
  • Payment or order processing service with TypeORM entities and repository layer
  • GraphQL gateway using resolvers backed by modular services
  • Authentication service using Passport strategies and JWT guards

FAQ

Does this kit include database setup?

Yes — it provides patterns and example configuration for TypeORM and notes how to swap in Prisma. You still supply connection details and migrations.

How are auth and roles handled?

Auth is implemented with Passport/JWT strategies, guards, and role decorators. Use guards on controllers or routes and define roles via decorators.