Boilerplate NestJS dengan Prisma, Winston, Swagger, dan Express Validator

Boilerplate NestJS dengan Prisma, Winston, Swagger, dan Express Validator
1. Pendahuluan
Artikel ini membahas cara membuat boilerplate NestJS yang lengkap dengan integrasi:
- Prisma sebagai ORM
- Winston untuk logging
- Swagger untuk dokumentasi API
- Express Validator untuk validasi input
Boilerplate ini memberikan dasar yang solid untuk membangun aplikasi NestJS yang robust, terstruktur, dan mudah dikembangkan.
2. Langkah-langkah Membuat Boilerplate
2.1. Instalasi dan Setup
1. Buat proyek baru dengan NestJS CLI:
nest new nestjs-boilerplate
2. Install dependensi yang diperlukan:
npm install @nestjs/swagger swagger-ui-express prisma @prisma/client winston express-validator
3. Setup Prisma:
npx prisma init
Konfigurasi koneksi database di file prisma/.env
:
DATABASE_URL="postgresql://user:password@localhost:5432/mydb?schema=public"
Buat model Prisma sederhana di prisma/schema.prisma
:
model User {
id Int @id @default(autoincrement())
name String
email String @unique
createdAt DateTime @default(now())
}
Jalankan migrasi untuk membuat tabel di database:
npx prisma migrate dev --name init
2.2. Setup Winston Logger
1. Install Winston:
npm install winston
2. Buat file logger src/logger/logger.service.ts
:
import { Injectable } from '@nestjs/common';
import { createLogger, transports, format } from 'winston';
@Injectable()
export class LoggerService {
private logger;
constructor() {
this.logger = createLogger({
level: 'info',
format: format.combine(
format.colorize(),
format.timestamp(),
format.printf(({ timestamp, level, message }) => {
return `${timestamp} [${level}]: ${message}`;
})
),
transports: [new transports.Console()],
});
}
log(message: string) {
this.logger.info(message);
}
error(message: string) {
this.logger.error(message);
}
warn(message: string) {
this.logger.warn(message);
}
}
2.3. Setup Swagger
Tambahkan Swagger di file src/main.ts
:
import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const config = new DocumentBuilder()
.setTitle('NestJS Boilerplate API')
.setDescription('API documentation for NestJS Boilerplate')
.setVersion('1.0')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document);
await app.listen(3000);
}
bootstrap();
2.4. Setup Express Validator
1. Install Express Validator:
npm install express-validator
2. Buat file validasi src/validation/create-user.validation.ts
:
import { body } from 'express-validator';
export const createUserValidation = [
body('name').isString().withMessage('Name should be a string'),
body('email').isEmail().withMessage('Email should be a valid email'),
];
2.5. Buat Service dan Controller untuk Pengguna (User)
Controller (src/users/user.controller.ts
)
import { Controller, Get, Post, Body, UsePipes, ValidationPipe } from '@nestjs/common';
import { ApiTags, ApiResponse } from '@nestjs/swagger';
import { UserService } from './user.service';
import { CreateUserDto } from './dto/create-user.dto';
import { User } from '@prisma/client';
import { createUserValidation } from 'src/validation/create-user.validation';
import { validationResult } from 'express-validator';
import { Request, Response, NextFunction } from 'express';
@ApiTags('users')
@Controller('users')
export class UserController {
constructor(private readonly userService: UserService) {}
@Post()
@UsePipes(new ValidationPipe())
@ApiResponse({ status: 201, description: 'User created successfully', type: CreateUserDto })
@ApiResponse({ status: 400, description: 'Invalid input' })
async create(@Body() createUserDto: CreateUserDto, req: Request, res: Response, next: NextFunction) {
await Promise.all(createUserValidation.map((validation) => validation.run(req)));
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
return this.userService.create(createUserDto);
}
@Get()
@ApiResponse({ status: 200, description: 'List of users', type: [CreateUserDto] })
async findAll(): Promise<User[]> {
return this.userService.findAll();
}
}
Service (src/users/user.service.ts
)
import { Injectable } from '@nestjs/common';
import { PrismaService } from 'src/prisma/prisma.service';
import { CreateUserDto } from './dto/create-user.dto';
import { User } from '@prisma/client';
@Injectable()
export class UserService {
constructor(private readonly prisma: PrismaService) {}
async create(createUserDto: CreateUserDto): Promise<User> {
return this.prisma.user.create({ data: createUserDto });
}
async findAll(): Promise<User[]> {
return this.prisma.user.findMany();
}
}
3. Kesimpulan
Dengan mengikuti langkah-langkah di atas, Anda telah berhasil membuat boilerplate NestJS dengan integrasi: ✅ Prisma untuk ORM ✅ Winston untuk logging ✅ Swagger untuk dokumentasi API ✅ Express Validator untuk validasi input
Boilerplate ini menyediakan fondasi yang solid untuk pengembangan lebih lanjut. Anda dapat menyesuaikannya dengan kebutuhan proyek Anda. 🚀