Refactor auth-service to iam-service and update related documentation

- Renamed auth-service to iam-service across various files for consistency.
- Updated Dockerfiles, deployment configurations, and documentation to reflect the service name change.
- Enhanced testing commands in documentation to point to the new iam-service.
- Removed outdated auth-service files and configurations to streamline the project structure.
- Improved bilingual documentation for clarity on the new service structure and usage.
This commit is contained in:
Ho Ngoc Hai
2025-12-30 20:54:21 +07:00
parent 7a4bda8da7
commit b104fafa85
246 changed files with 35630 additions and 2867 deletions

View File

@@ -0,0 +1,562 @@
# Comment Code / Viết Comment Code
> **EN**: Guidelines for adding comprehensive bilingual code comments (English and Vietnamese) to improve code readability for international and Vietnamese teams.
> **VI**: Hướng dẫn thêm comments song ngữ (tiếng Anh và tiếng Việt) để cải thiện khả năng đọc code cho các đội quốc tế và Việt Nam.
## Overview / Tổng Quan
**EN**: Code comments are essential for maintaining and understanding codebase, especially in a bilingual development environment. This guide provides comprehensive patterns for writing clear, consistent, and helpful comments in both English and Vietnamese across the GoodGo microservices platform. It covers JSDoc documentation, inline comments, special comment types, and best practices for effective code documentation.
**VI**: Comments code là điều cần thiết để bảo trì và hiểu codebase, đặc biệt trong môi trường phát triển song ngữ. Hướng dẫn này cung cấp các patterns toàn diện để viết comments rõ ràng, nhất quán và hữu ích bằng cả tiếng Anh và tiếng Việt trên nền tảng microservices GoodGo. Nó bao gồm tài liệu JSDoc, inline comments, các loại comment đặc biệt, và best practices cho tài liệu code hiệu quả.
## When to Use / Khi Nào Sử Dụng
**EN**: Use bilingual commenting patterns when:
- Adding comments to new code
- Documenting existing code
- Creating JSDoc/TSDoc documentation
- Writing function/class descriptions
- Explaining complex logic or algorithms
- Adding inline comments for clarification
- Documenting API endpoints and interfaces
- Explaining configuration and setup code
- Writing security-critical code documentation
- Creating error handling documentation
**VI**: Sử dụng các patterns comment song ngữ khi:
- Thêm comments vào code mới
- Tài liệu hóa code hiện có
- Tạo tài liệu JSDoc/TSDoc
- Viết mô tả functions/classes
- Giải thích logic hoặc thuật toán phức tạp
- Thêm inline comments để làm rõ
- Tài liệu hóa API endpoints và interfaces
- Giải thích code cấu hình và setup
- Viết tài liệu code bảo mật quan trọng
- Tạo tài liệu xử lý lỗi
## Key Concepts / Khái Niệm Chính
### Comment Format / Định Dạng Comment
All comments in the GoodGo project should be bilingual, with English (EN) followed by Vietnamese (VI) translations.
**Pattern**:
```
// EN: [English explanation]
// VI: [Vietnamese explanation]
```
### Comment Types / Các Loại Comment
1. **Single-line Comments** (`//`): For brief explanations
2. **Multi-line Comments** (`/* */`): For longer explanations
3. **JSDoc Comments** (`/** */`): For function, class, and API documentation
4. **Prisma Comments** (`///`): For database schema documentation
## Common Patterns / Các Pattern Thường Dùng
### Single-line Comments / Comments Một Dòng
Use single-line comments for brief explanations of code behavior.
```typescript
// EN: Initialize database connection
// VI: Khởi tạo kết nối database
const db = await createConnection();
// EN: Enable detailed logging in development, minimal in production
// VI: Bật ghi log chi tiết trong development, tối thiểu trong production
const logLevel = process.env.NODE_ENV === 'development' ? 'debug' : 'error';
```
**Real Example**: [`services/iam-service/src/config/database.config.ts`](../../../services/iam-service/src/config/database.config.ts)
### Multi-line Comments / Comments Nhiều Dòng
Use multi-line comments for detailed explanations or step-by-step processes.
```typescript
/**
* EN: Validates user credentials and returns JWT token
* VI: Xác thực thông tin đăng nhập và trả về JWT token
*
* @param email - User email address / Địa chỉ email người dùng
* @param password - User password / Mật khẩu người dùng
* @returns JWT token / Mã JWT token
* @throws AuthenticationError if credentials invalid / Lỗi xác thực nếu thông tin không hợp lệ
*/
async function login(email: string, password: string): Promise<string> {
// EN: Implementation here
// VI: Implementation ở đây
}
```
### Function Documentation / Tài Liệu Function
Use JSDoc format for all public functions with bilingual descriptions.
```typescript
/**
* EN: Calculates the total price including tax and discount
* VI: Tính tổng giá bao gồm thuế và giảm giá
*
* @param basePrice - Original price / Giá gốc
* @param taxRate - Tax rate (0-1) / Tỷ lệ thuế (0-1)
* @param discount - Discount amount / Số tiền giảm giá
* @returns Final price / Giá cuối cùng
*/
function calculateTotal(
basePrice: number,
taxRate: number,
discount: number
): number {
// EN: Apply discount first
// VI: Áp dụng giảm giá trước
const discountedPrice = basePrice - discount;
// EN: Then calculate tax
// VI: Sau đó tính thuế
const tax = discountedPrice * taxRate;
return discountedPrice + tax;
}
```
**Real Example**: [`services/iam-service/src/modules/feature/feature.service.ts`](../../../services/iam-service/src/modules/feature/feature.service.ts)
### Class Documentation / Tài Liệu Class
Document classes with bilingual descriptions and explain their purpose.
```typescript
/**
* EN: Service for managing features in the system
* VI: Service để quản lý các features trong hệ thống
*/
export class FeatureService {
/**
* EN: Create a new feature
* VI: Tạo một feature mới
*
* @param data - Feature data / Dữ liệu feature
* @returns Created feature / Feature đã tạo
*/
async create(data: { name: string; title?: string }) {
// Implementation
}
}
```
**Real Example**: [`services/iam-service/src/modules/feature/feature.service.ts`](../../../services/iam-service/src/modules/feature/feature.service.ts)
### Interface/Type Documentation / Tài Liệu Interface/Type
Document interfaces and types to explain their structure and purpose.
```typescript
/**
* EN: User data transfer object
* VI: Đối tượng truyền dữ liệu người dùng
*/
interface UserDto {
/** EN: Unique user identifier / VI: Mã định danh duy nhất */
id: string;
/** EN: User email address / VI: Địa chỉ email người dùng */
email: string;
/** EN: User display name / VI: Tên hiển thị người dùng */
name: string;
/** EN: User role for authorization / VI: Vai trò người dùng để phân quyền */
role: 'admin' | 'user' | 'guest';
}
```
### Configuration Comments / Comments Cấu Hình
Document configuration files and environment variables with clear explanations.
```typescript
/**
* EN: Prisma client instance configured for the application
* VI: Instance Prisma client được cấu hình cho ứng dụng
*/
export const prisma = new PrismaClient({
// EN: Enable detailed logging in development, minimal in production
// VI: Bật ghi log chi tiết trong development, tối thiểu trong production
log: process.env.NODE_ENV === 'development' ? ['query', 'error', 'warn'] : ['error'],
});
/**
* EN: Establish database connection on application startup
* VI: Thiết lập kết nối database khi khởi động ứng dụng
*/
export const connectDatabase = async (): Promise<void> => {
try {
// EN: Connect to database using Prisma
// VI: Kết nối tới database sử dụng Prisma
await prisma.$connect();
logger.info('Database connected successfully / Kết nối database thành công');
} catch (error) {
// EN: Log error and exit if database connection fails
// VI: Ghi log lỗi và thoát nếu kết nối database thất bại
logger.error('Database connection failed / Kết nối database thất bại', { error });
process.exit(1);
}
};
```
**Real Example**: [`services/iam-service/src/config/database.config.ts`](../../../services/iam-service/src/config/database.config.ts)
### Middleware Documentation / Tài Liệu Middleware
Document middleware functions with their purpose and behavior.
```typescript
/**
* EN: Authentication middleware to verify JWT tokens
* VI: Middleware xác thực để kiểm tra JWT token
*/
export function authMiddleware(
req: Request,
res: Response,
next: NextFunction
) {
// EN: Extract token from Authorization header
// VI: Lấy token từ header Authorization
const authHeader = req.headers.authorization;
const token = authHeader?.replace('Bearer ', '');
if (!token) {
return res.status(401).json({
success: false,
error: {
code: 'NO_TOKEN',
message: 'Authentication required / Yêu cầu xác thực',
},
});
}
try {
// EN: Verify token and extract payload
// VI: Xác minh token và lấy payload
const payload = jwt.verify(token, JWT_SECRET);
req.user = payload;
next();
} catch (error) {
return res.status(401).json({
success: false,
error: {
code: 'INVALID_TOKEN',
message: 'Invalid or expired token / Token không hợp lệ hoặc hết hạn',
},
});
}
}
```
### Prisma Schema Comments / Comments Schema Prisma
Use triple-slash comments (`///`) for Prisma schema documentation.
```prisma
/// EN: User model for authentication and profile
/// VI: Model người dùng cho xác thực và hồ sơ
model User {
/// EN: Unique identifier / VI: Mã định danh duy nhất
id String @id @default(cuid())
/// EN: User email (unique) / VI: Email người dùng (duy nhất)
email String @unique
/// EN: Hashed password / VI: Mật khẩu đã mã hóa
password String
/// EN: Display name / VI: Tên hiển thị
name String
/// EN: Account creation timestamp / VI: Thời gian tạo tài khoản
createdAt DateTime @default(now())
/// EN: Last update timestamp / VI: Thời gian cập nhật cuối
updatedAt DateTime @updatedAt
@@map("users")
}
```
### Test Comments / Comments Test
Document test setup and explain test scenarios in both languages.
```typescript
// EN: Mock environment variables for tests
// VI: Mock biến môi trường cho tests
process.env.NODE_ENV = 'test';
process.env.DATABASE_URL = 'postgresql://test:test@localhost:5432/test_db';
// EN: Mock external services to avoid real network calls
// VI: Mock các service bên ngoài để tránh gọi mạng thật
jest.mock('@goodgo/logger', () => ({
logger: {
info: jest.fn(),
error: jest.fn(),
},
}));
describe('FeatureService', () => {
it('should create a feature successfully', async () => {
// EN: Arrange
// VI: Chuẩn bị
const testData = { name: 'test-feature' };
// EN: Act
// VI: Thực hiện
const result = await service.create(testData);
// EN: Assert
// VI: Kiểm tra
expect(result).toBeDefined();
});
});
```
**Real Example**: [`services/iam-service/src/__tests__/setupTests.ts`](../../../services/iam-service/src/__tests__/setupTests.ts)
### Complex Logic Comments / Comments Logic Phức Tạp
When explaining complex algorithms or business logic, break it down into steps.
```typescript
// EN: Step 1: Validate input parameters
// VI: Bước 1: Xác thực tham số đầu vào
if (!email || !password) {
throw new ValidationError('Email and password required');
}
// EN: Step 2: Check if user exists in database
// VI: Bước 2: Kiểm tra xem người dùng có tồn tại trong database
const user = await prisma.user.findUnique({ where: { email } });
if (!user) {
throw new NotFoundError('User not found');
}
// EN: Step 3: Verify password hash
// VI: Bước 3: Xác minh hash mật khẩu
const isValidPassword = await bcrypt.compare(password, user.password);
if (!isValidPassword) {
throw new AuthenticationError('Invalid credentials');
}
// EN: Step 4: Generate and return JWT token
// VI: Bước 4: Tạo và trả về JWT token
const token = jwt.sign({ userId: user.id }, JWT_SECRET);
return { token, user };
```
## Special Comment Types / Các Loại Comment Đặc Biệt
### TODO Comments / Comments TODO
Use TODO comments for future improvements with bilingual descriptions.
```typescript
// TODO EN: Implement caching for better performance
// TODO VI: Triển khai caching để cải thiện hiệu suất
// TODO EN: Add rate limiting to prevent abuse
// TODO VI: Thêm rate limiting để ngăn chặn lạm dụng
```
### FIXME Comments / Comments FIXME
Use FIXME comments for code that needs fixing.
```typescript
// FIXME EN: This causes memory leak, needs refactoring
// FIXME VI: Đoạn này gây rò rỉ bộ nhớ, cần refactor
// FIXME EN: Temporary workaround, should implement proper solution
// FIXME VI: Giải pháp tạm thời, nên triển khai giải pháp đúng đắn
```
### WARNING Comments / Comments CẢNH BÁO
Use WARNING comments for code that requires special attention.
```typescript
// WARNING EN: Do not modify this without updating the database schema
// WARNING VI: Không sửa đổi phần này mà không cập nhật schema database
// WARNING EN: This function modifies global state, use with caution
// WARNING VI: Function này thay đổi global state, sử dụng cẩn thận
```
### NOTE Comments / Comments GHI CHÚ
Use NOTE comments for important information or explanations.
```typescript
// NOTE EN: This is intentionally async to avoid blocking the event loop
// NOTE VI: Đây là async có chủ ý để tránh block event loop
// NOTE EN: Priority: Docker Compose > .env.local > .env > System environment
// NOTE VI: Ưu tiên: Docker Compose > .env.local > .env > Môi trường hệ thống
```
## Best Practices / Thực Hành Tốt Nhất
### Comment Placement / Vị Trí Comment
- ✅ Place bilingual comments together (EN first, then VI) / Đặt comments song ngữ cùng nhau (EN trước, sau đó VI)
- ✅ Keep comments close to the code they describe / Giữ comments gần với code mà chúng mô tả
- ✅ Use JSDoc format for functions and classes / Sử dụng format JSDoc cho functions và classes
- ✅ Update comments when code changes / Cập nhật comments khi code thay đổi
### Comment Content / Nội Dung Comment
-**DO**: Explain WHY, not WHAT (code shows what) / Giải thích TẠI SAO, không phải CÁI GÌ
-**DO**: Document complex logic and business rules / Tài liệu hóa logic phức tạp và quy tắc nghiệp vụ
-**DO**: Include parameter descriptions and return types / Bao gồm mô tả tham số và kiểu trả về
-**DO**: Document error conditions and exceptions / Tài liệu hóa điều kiện lỗi và ngoại lệ
-**DON'T**: State the obvious / Không nói điều hiển nhiên
-**DON'T**: Write redundant comments / Không viết comments thừa
-**DON'T**: Comment out code (use version control instead) / Không comment code (sử dụng version control)
### Language Guidelines / Hướng Dẫn Ngôn Ngữ
**English / Tiếng Anh**:
- Use clear, concise technical English / Sử dụng tiếng Anh kỹ thuật rõ ràng, ngắn gọn
- Use proper technical terminology / Sử dụng thuật ngữ kỹ thuật đúng
- Be specific and actionable / Cụ thể và có thể thực hiện
**Vietnamese / Tiếng Việt**:
- Use proper Vietnamese technical terms / Sử dụng thuật ngữ kỹ thuật tiếng Việt đúng
- Keep translations accurate and natural / Giữ bản dịch chính xác và tự nhiên
- Use consistent terminology across codebase / Sử dụng thuật ngữ nhất quán trên codebase
- Prefer technical Vietnamese terms over literal translations / Ưu tiên thuật ngữ kỹ thuật Việt hơn dịch theo nghĩa đen
### Documentation Priority / Ưu Tiên Tài Liệu
**High Priority** (Always document / Luôn tài liệu hóa):
- Public APIs and exported functions / API công khai và functions được export
- Complex algorithms and business logic / Thuật toán phức tạp và logic nghiệp vụ
- Security-critical code / Code bảo mật quan trọng
- Configuration and environment setup / Cấu hình và thiết lập môi trường
- Error handling strategies / Chiến lược xử lý lỗi
**Medium Priority** (Document when helpful / Tài liệu khi hữu ích):
- Helper functions with non-obvious behavior / Helper functions có hành vi không rõ ràng
- Data transformations / Chuyển đổi dữ liệu
- Integration points with external services / Điểm tích hợp với services bên ngoài
**Low Priority** (Optional / Tùy chọn):
- Simple getters/setters / Getters/setters đơn giản
- Self-explanatory code / Code tự giải thích
- Standard CRUD operations / Các thao tác CRUD tiêu chuẩn
## Examples from Project / Ví Dụ Từ Dự Án
### Real Comment Examples / Ví Dụ Comment Thực Tế
1. **Service Comments**: [`services/iam-service/src/modules/feature/feature.service.ts`](../../../services/iam-service/src/modules/feature/feature.service.ts)
2. **Config Comments**: [`services/iam-service/src/config/database.config.ts`](../../../services/iam-service/src/config/database.config.ts)
3. **Test Comments**: [`services/iam-service/src/__tests__/setupTests.ts`](../../../services/iam-service/src/__tests__/setupTests.ts)
4. **Jest Config Comments**: [`services/iam-service/jest.config.ts`](../../../services/iam-service/jest.config.ts)
### Comment Patterns in Different Contexts / Patterns Comment Trong Các Ngữ Cảnh Khác Nhau
- **Controllers**: Document API endpoints and request/response handling
- **Services**: Document business logic and data processing
- **Middleware**: Document authentication, authorization, and request processing
- **Repositories**: Document database operations and query logic
- **Config Files**: Document configuration options and environment variables
- **Tests**: Document test scenarios and setup procedures
## Quick Reference / Tham Khảo Nhanh
### Function Comment Template / Template Comment Function
```typescript
/**
* EN: [Brief description in English]
* VI: [Mô tả ngắn gọn bằng tiếng Việt]
*
* @param paramName - EN description / VI mô tả
* @returns EN description / VI mô tả
* @throws ErrorType EN when / VI khi nào
*/
```
### Inline Comment Template / Template Inline Comment
```typescript
// EN: [English explanation]
// VI: [Giải thích tiếng Việt]
```
### Complex Block Template / Template Block Phức Tạp
```typescript
// EN: Step N: [What this block does]
// VI: Bước N: [Block này làm gì]
```
### Class Comment Template / Template Comment Class
```typescript
/**
* EN: [Class purpose in English]
* VI: [Mục đích class bằng tiếng Việt]
*/
export class ClassName {
/**
* EN: [Property description]
* VI: [Mô tả property]
*/
private property: string;
}
```
### Interface Comment Template / Template Comment Interface
```typescript
/**
* EN: [Interface purpose in English]
* VI: [Mục đích interface bằng tiếng Việt]
*/
interface InterfaceName {
/** EN: Property description / VI: Mô tả property */
property: string;
}
```
## Related Skills / Skills Liên Quan
- **[Testing Patterns](./testing-patterns.md)**: Writing comments in test files / Viết comments trong file test
- **[API Design](./api-design.md)**: Documenting API endpoints / Tài liệu hóa API endpoints
- **[Documentation](./documentation.md)**: Writing technical documentation / Viết tài liệu kỹ thuật
- **[Project Rules](./project-rules.md)**: Code organization and standards / Tổ chức code và tiêu chuẩn
## Resources / Tài Nguyên
### Documentation Standards / Tiêu Chuẩn Tài Liệu
- [JSDoc Documentation](https://jsdoc.app/)
- [TypeScript JSDoc](https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html)
- [TSDoc Specification](https://tsdoc.org/)
### Internal Documentation / Tài Liệu Nội Bộ
- [Documentation Writing Guidelines](./documentation.md)
- [API Design Standards](./api-design.md)
- [Project Coding Standards](./project-rules.md)
### Tools / Công Cụ
- **JSDoc**: Generate API documentation from comments
- **ESLint**: Enforce comment style and completeness
- **Prettier**: Format comments consistently
- **VS Code**: IntelliSense uses JSDoc comments for better autocomplete