Writing Clean and Maintainable Code in NestJS
Part 12 of 12
Documentation as Part of Clean Code in NestJS
Good documentation is an essential part of clean and maintainable code. However, excessive or outdated comments can create more confusion than clarity. Instead of writing unnecessary comments, we should focus on:
- Writing minimal but effective documentation
- Using TypeScript types to reduce the need for comments
- Generating API docs automatically with Swagger
1. Writing Minimal but Effective Documentation
Many developers either over-document or under-document their code.
The goal should be self-explanatory code with minimal but useful documentation.
✅ When Should You Write Documentation?
- Complex Business Logic – When code isn't obvious from reading
- Public APIs – For consumers using your API
- Configuration Files – For environment variables, setup instructions
- Project Setup – How to install, configure, and run the app
📌 Example: Well-Documented README
README.md
# My NestJS API
## 📌 Installation
```sh
git clone https://github.com/your-repo/nestjs-api.git
cd nestjs-api
npm install
```
🚀 Running the App
npm run start
📖 API Documentation
Swagger is available at http://localhost:3000/docs.
✅ **Minimal yet useful** – Covers setup and API documentation
---
## 2. Using TypeScript Types to Reduce the Need for Comments
Instead of writing unnecessary comments, **leverage TypeScript types** to make the code self-explanatory.
---
### ❌ **Bad Example: Over-Commenting**
```ts
class User {
// User ID
id: string;
// User name
name: string;
// User email address
email: string;
}
🚨 Problem: The comments provide no extra value
✅ Good Example: Using TypeScript Types
class User {
id: string;
name: string;
email: string;
}
✅ Clear and concise – No redundant comments
✅ Using Interfaces for Clarity
interface User {
id: string;
name: string;
email: string;
}
✅ Self-explanatory structure – No need for comments
✅ Documenting Function Parameters with JSDoc
If a function's behavior isn't obvious, use JSDoc comments.
/**
* Fetches a user by ID.
* @param userId - The unique identifier of the user
* @returns The user object if found
*/
function getUser(userId: string): User {
return { id: userId, name: 'John Doe', email: 'john@example.com' };
}
✅ Only necessary documentation
3. Generating API Docs Automatically with Swagger
NestJS provides Swagger integration for auto-generating API documentation.
📌 Step 1: Install Swagger
npm install --save @nestjs/swagger swagger-ui-express
📌 Step 2: Configure Swagger in main.ts
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const config = new DocumentBuilder()
.setTitle('My API')
.setDescription('API documentation for my NestJS app')
.setVersion('1.0')
.addBearerAuth()
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('docs', app, document);
await app.listen(3000);
}
✅ Now, Swagger docs will be available at http://localhost:3000/docs
📌 Step 3: Document Endpoints with Decorators
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
@ApiTags('Users')
@Controller('users')
export class UserController {
constructor(private readonly userService: UserService) {}
@Get(':id')
@ApiOperation({ summary: 'Get user by ID' })
@ApiResponse({ status: 200, description: 'Returns the user data' })
async getUser(@Param('id') id: string) {
return this.userService.getUserById(id);
}
}
✅ Swagger automatically generates API docs
✅ No need for separate documentation files
4. Summary: Best Practices for Clean Documentation
✅ Write minimal but effective documentation – Only where necessary
✅ Leverage TypeScript types instead of redundant comments
✅ Use Swagger to generate API docs automatically
This concludes our series on Clean Code in TypeScript & NestJS! 🎉
How do you handle documentation in your projects? Let me know in the comments!