NestJSAdvanced
NestJS Best Practices
Structure, DTO everywhere, error handling, performance, security — সেরা অভ্যাস বাংলায়।
15টি অংশবাংলা ভাষায়
1. Proper Folder Structure
src/
├── modules/ # feature modules
│ ├── users/
│ │ ├── users.module.ts
│ │ ├── users.controller.ts
│ │ ├── users.service.ts
│ │ ├── dto/
│ │ ├── schemas/ (বা entities/)
│ │ └── test files
│ └── auth/
├── common/ # shared
│ ├── guards/
│ ├── pipes/
│ ├── interceptors/
│ ├── decorators/
│ └── filters/
├── types/ # shared interfaces
├── config/
└── main.ts2. DTO সর্বত্র
// ❌ avoid — any
create(@Body() body: any) {}
// ✅ DTO
@Post()
create(@Body() dto: CreateUserDto) {}
// separate dto per operation
// CreateUserDto, UpdateUserDto, LoginDto3. Single Responsibility
// Controller → HTTP layer শুধু
// Service → business logic
// Repository/Model → data access
// Module → grouping
// ❌ controller-এ DB logic
@Get()
async findAll(@Query() q: any) {
const db = await getDb();
return db.collection('users').find().toArray();
}
// ✅ service-এ
@Get()
findAll() {
return this.usersService.findAll();
}4. Global Validation & Filters
main.ts — production baselinetypescript
typescript
import { ValidationPipe, Logger } from "@nestjs/common";
import { HttpAdapterHost, NestFactory } from "@nestjs/core";
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.setGlobalPrefix("api/v1"); // versioning
app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));
app.enableCors({ origin: process.env.FRONTEND_URL });
app.useLogger(["error", "warn", "log"]);
await app.listen(3000);
}
bootstrap();5. Performance
# build production
npm run build
# run — NODE_ENV=production + cluster
pm2 start dist/main.js -i max
# enable gzip (nginx বা compression)
# app.use(compression()) — अगर application server6. Security Checklist
// main.ts
import { NestFactory } from "@nestjs/core";
import { helmet } from "helmet";
// helmet
app.use(helmet());
// rate limit (nestjs-rate-limiter package)
app.enableCors({
origin: ["https://myapp.com"],
credentials: true,
});# extra packages
npm i helmet express-rate-limit| ✔ | অভ্যাস |
|---|---|
| ✔ | DTO + class-validator (whitelist) |
| ✔ | Guards দিয়ে authorization |
| ✔ | Swagger docs (api tags) |
| ✔ | Global exception format |
| ✔ | ConfigModule + env validation |
| ✔ | Unit + e2e test |
| ✔ | Controller thin, Service logic |
| ✔ | Helmet + rate limit + CORS |
| ✔ | Versioned prefix /api/v1 |
| ✔ | Logging (nestjs Logger/class-validator) |
Opensource reference
NestJS-এর অফিসিয়াল nestjs/sample repositories প্রতিটি concept-এর reference — শুরুতে ওগুলো পড়ে অনুসরণ করা ভালো।
শেষ প্যারায় নিজে practice করুন — কোড কপি করে নিজের এডিটরে চালিয়ে দেখুন।