- Added request/response flow diagrams to api-design and api-gateway-advanced skills for better visualization of processes. - Introduced configuration loading flow in configuration-management skill to clarify the configuration process. - Included error propagation flow in error-handling-patterns skill to illustrate error handling across layers. - Enhanced various skills with additional diagrams to improve understanding of complex concepts. These updates aim to provide clearer guidance and improve the overall documentation experience for developers.
14 KiB
14 KiB
name, description
| name | description |
|---|---|
| comment-code | Add bilingual code comments in Vietnamese and English for better documentation. Use when adding comments to code, documenting functions/classes, or when user requests Vietnamese/English documentation. |
Bilingual Code Comments
Add comprehensive code comments in both Vietnamese and English to improve code readability for international and Vietnamese teams.
When to Use
- Adding comments to new code
- Documenting existing code
- Creating JSDoc/TSDoc documentation
- Writing function/class descriptions
- Explaining complex logic
- Adding inline comments
Comment Structure
The following diagram illustrates the structure and hierarchy of comment types used in the GoodGo codebase:
graph TB
subgraph CommentTypes["Comment Types"]
SingleLine["Single-line Comments<br/>// EN: ...<br/>// VI: ..."]
MultiLine["Multi-line Comments<br/>/* EN: ...<br/>VI: ... */"]
JSDoc["JSDoc Comments<br/>/** EN: ...<br/>VI: ... */"]
Prisma["Prisma Comments<br/>/// EN: ...<br/>VI: ..."]
end
subgraph Contexts["Code Contexts"]
Functions["Functions"]
Classes["Classes"]
Interfaces["Interfaces/Types"]
Components["React Components"]
Controllers["API Controllers"]
Middleware["Middleware"]
Schema["Prisma Schema"]
Config["Configuration"]
end
subgraph SpecialTypes["Special Comment Types"]
TODO["TODO Comments"]
FIXME["FIXME Comments"]
WARNING["WARNING Comments"]
NOTE["NOTE Comments"]
end
subgraph Format["Bilingual Format"]
EN["English (EN)<br/>First"]
VI["Vietnamese (VI)<br/>Second"]
end
JSDoc --> Functions
JSDoc --> Classes
JSDoc --> Interfaces
JSDoc --> Components
JSDoc --> Controllers
JSDoc --> Middleware
SingleLine --> Config
SingleLine --> SpecialTypes
MultiLine --> Functions
MultiLine --> Classes
Prisma --> Schema
Format --> CommentTypes
Format --> Contexts
Format --> SpecialTypes
style CommentTypes fill:#e1f5ff
style Contexts fill:#fff4e1
style SpecialTypes fill:#ffe1f5
style Format fill:#e1ffe1
Documentation Flow
The following diagram shows the decision flow for adding comments to code:
flowchart TD
Start([Start: Writing Code]) --> CheckType{What type of<br/>code element?}
CheckType -->|Public API| HighPriority[High Priority:<br/>Always Document]
CheckType -->|Complex Logic| HighPriority
CheckType -->|Security Code| HighPriority
CheckType -->|Config/Setup| HighPriority
CheckType -->|Error Handling| HighPriority
CheckType -->|Helper Function| MediumPriority[Medium Priority:<br/>Document if Helpful]
CheckType -->|Data Transform| MediumPriority
CheckType -->|External Integration| MediumPriority
CheckType -->|Simple Getter/Setter| LowPriority[Low Priority:<br/>Optional]
CheckType -->|Self-explanatory| LowPriority
CheckType -->|Standard CRUD| LowPriority
HighPriority --> ChooseFormat{Choose Comment<br/>Format}
MediumPriority --> ChooseFormat
LowPriority --> ChooseFormat
ChooseFormat -->|Function/Class| UseJSDoc[Use JSDoc Format<br/>/** EN: ...<br/>VI: ... */]
ChooseFormat -->|Brief Explanation| UseSingleLine[Use Single-line<br/>// EN: ...<br/>// VI: ...]
ChooseFormat -->|Multi-step Process| UseMultiLine[Use Multi-line<br/>/* EN: ...<br/>VI: ... */]
ChooseFormat -->|Prisma Schema| UsePrisma[Use Prisma Format<br/>/// EN: ...<br/>VI: ...]
UseJSDoc --> AddParams[Add @param tags<br/>Add @returns tag<br/>Add @throws if needed]
UseSingleLine --> WriteBilingual[Write Bilingual:<br/>EN first, VI second]
UseMultiLine --> WriteBilingual
UsePrisma --> WriteBilingual
AddParams --> WriteBilingual
WriteBilingual --> CheckSpecial{Special<br/>Comment Type?}
CheckSpecial -->|Future Work| AddTODO[Add TODO prefix]
CheckSpecial -->|Needs Fix| AddFIXME[Add FIXME prefix]
CheckSpecial -->|Important Warning| AddWARNING[Add WARNING prefix]
CheckSpecial -->|Important Note| AddNOTE[Add NOTE prefix]
CheckSpecial -->|No| End([Done])
AddTODO --> End
AddFIXME --> End
AddWARNING --> End
AddNOTE --> End
style HighPriority fill:#ffcccc
style MediumPriority fill:#ffffcc
style LowPriority fill:#ccffcc
style UseJSDoc fill:#cce5ff
style UseSingleLine fill:#cce5ff
style UseMultiLine fill:#cce5ff
style UsePrisma fill:#cce5ff
Comment Format
Single-line Comments
// EN: Initialize database connection
// VI: Khởi tạo kết nối database
const db = await createConnection();
Multi-line Comments
/**
* 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> {
// Implementation
}
Core Comment Patterns
Function Documentation
/**
* 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;
}
Class Documentation
/**
* EN: Handles user authentication and authorization
* VI: Xử lý xác thực và phân quyền người dùng
*/
export class AuthService {
/**
* EN: JWT secret key from environment
* VI: Khóa bí mật JWT từ biến môi trường
*/
private readonly jwtSecret: string;
/**
* EN: Verify JWT token and return user payload
* VI: Xác minh JWT token và trả về thông tin người dùng
*
* @param token - JWT token to verify / JWT token cần xác minh
* @returns User payload / Thông tin người dùng
* @throws TokenExpiredError if token expired / Lỗi token hết hạn
*/
async verifyToken(token: string): Promise<UserPayload> {
// Implementation
}
}
Interface/Type Documentation
/**
* 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';
}
React Components
/**
* EN: User profile card component
* VI: Component thẻ hồ sơ người dùng
*
* @param user - User data to display / Dữ liệu người dùng để hiển thị
* @param onEdit - Callback when edit button clicked / Callback khi nhấn nút chỉnh sửa
*/
export function UserCard({ user, onEdit }: UserCardProps) {
// EN: Local state for loading status
// VI: State cục bộ cho trạng thái loading
const [isLoading, setIsLoading] = useState(false);
return (
<div className="user-card">
{/* EN: Display user avatar / VI: Hiển thị avatar người dùng */}
<img src={user.avatar} alt={user.name} />
{/* EN: User information section / VI: Phần thông tin người dùng */}
<div className="user-info">
<h3>{user.name}</h3>
<p>{user.email}</p>
</div>
</div>
);
}
Prisma Schema
/// 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")
}
API Controllers
/**
* EN: User management controller
* VI: Controller quản lý người dùng
*/
export class UserController {
/**
* EN: Get user by ID
* VI: Lấy thông tin người dùng theo ID
*
* GET /api/users/:id
*/
async getById(req: Request, res: Response) {
try {
// EN: Extract user ID from params
// VI: Lấy ID người dùng từ params
const { id } = req.params;
// EN: Fetch user from database
// VI: Lấy người dùng từ database
const user = await this.userService.findById(id);
if (!user) {
return res.status(404).json({
success: false,
error: {
code: 'USER_NOT_FOUND',
message: 'User not found / Không tìm thấy người dùng',
},
});
}
return res.json({
success: true,
data: user,
});
} catch (error) {
logger.error('Failed to get user', { error, userId: req.params.id });
return res.status(500).json({
success: false,
error: {
code: 'INTERNAL_ERROR',
message: 'Internal server error / Lỗi máy chủ nội bộ',
},
});
}
}
}
Middleware
/**
* 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',
},
});
}
}
Best Practices
1. Comment Placement
- Place bilingual comments together (EN first, then VI)
- Keep comments close to the code they describe
- Use JSDoc format for functions and classes
2. Comment Content
- DO: Explain WHY, not WHAT (code shows what)
- DO: Document complex logic and business rules
- DO: Include parameter descriptions and return types
- DO: Document error conditions and exceptions
- DON'T: State the obvious
- DON'T: Write redundant comments
3. Language Guidelines
- English: Use clear, concise technical English
- Vietnamese: Use proper Vietnamese technical terms
- Keep translations accurate and natural
- Use consistent terminology across codebase
4. Special Cases
TODO Comments
// TODO EN: Implement caching for better performance
// TODO VI: Triển khai caching để cải thiện hiệu suất
FIXME Comments
// FIXME EN: This causes memory leak, needs refactoring
// FIXME VI: Đoạn này gây rò rỉ bộ nhớ, cần refactor
WARNING Comments
// 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
5. Documentation Priority
High Priority (Always document):
- Public APIs and exported functions
- Complex algorithms and business logic
- Security-critical code
- Configuration and environment setup
- Error handling strategies
Medium Priority (Document when helpful):
- Helper functions with non-obvious behavior
- Data transformations
- Integration points with external services
Low Priority (Optional):
- Simple getters/setters
- Self-explanatory code
- Standard CRUD operations
Integration with Project Rules
When commenting code in this project:
- Follow the code organization from
project-rulesskill - Use consistent terminology with project documentation
- Align with the API response format standards
- Document according to the testing standards
- Include security considerations where relevant
Quick Reference
Function Comment Template
/**
* 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
// EN: [English explanation]
// VI: [Giải thích tiếng Việt]
Complex Block Template
// EN: Step N: [What this block does]
// VI: Bước N: [Block này làm gì]