# Mermaid Diagram Guide / Hướng dẫn Sơ đồ Mermaid ## Overview / Tổng quan **EN**: This guide helps you choose the right Mermaid diagram type for your documentation and provides examples for common use cases. **VI**: Hướng dẫn này giúp bạn chọn loại sơ đồ Mermaid phù hợp cho tài liệu của bạn và cung cấp ví dụ cho các trường hợp sử dụng phổ biến. ## Quick Reference / Tham chiếu Nhanh | Diagram Type / Loại | Use For / Sử dụng cho | Complexity / Độ phức tạp | |----------------------|------------------------|---------------------------| | **Flowchart** | Workflows, decision trees / Quy trình, cây quyết định | ⭐⭐ | | **Sequence Diagram** | API interactions, request flows / Tương tác API, luồng request | ⭐⭐⭐ | | **Class Diagram** | Code structure, patterns / Cấu trúc code, patterns | ⭐⭐⭐ | | **Graph** | System architecture, dependencies / Kiến trúc hệ thống, dependencies | ⭐⭐ | | **ER Diagram** | Database schema / Schema database | ⭐⭐⭐ | | **Gantt** | Timeline, project schedule / Timeline, lịch trình dự án | ⭐⭐ | | **C4 Diagram** | System context, containers / Bối cảnh hệ thống, containers | ⭐⭐⭐⭐ | --- ## 1. Flowcharts / Sơ đồ Luồng ### When to Use / Khi nào sử dụng **EN**: Use flowcharts for: - Step-by-step guides and workflows - Decision trees and conditional logic - Process flows with multiple branches - Troubleshooting procedures **VI**: Sử dụng flowcharts cho: - Hướng dẫn từng bước và quy trình - Cây quyết định và logic điều kiện - Luồng quy trình với nhiều nhánh - Thủ tục khắc phục sự cố ### Basic Flowchart ```mermaid flowchart TD Start([Start]) --> Input[Get Input] Input --> Check{Valid?} Check -->|Yes| Process[Process Data] Check -->|No| Error[Show Error] Process --> Output[Return Result] Output --> End([End]) Error --> End style Start fill:#e1f5ff style End fill:#d4edda style Check fill:#fff3cd style Error fill:#f8d7da ``` **Code**: ````markdown ```mermaid flowchart TD Start([Start]) --> Input[Get Input] Input --> Check{Valid?} Check -->|Yes| Process[Process Data] Check -->|No| Error[Show Error] Process --> Output[Return Result] Output --> End([End]) Error --> End style Start fill:#e1f5ff style End fill:#d4edda style Check fill:#fff3cd style Error fill:#f8d7da ``` ```` ### Advanced Flowchart with Subgraphs ```mermaid flowchart LR A[Client Request] --> B{Auth?} B -->|No| C[401 Unauthorized] B -->|Yes| D[Process] subgraph Processing["Request Processing"] D --> E[Validate Input] E --> F[Execute Logic] F --> G[Format Response] end G --> H[Return 200 OK] C --> I[End] H --> I style Processing fill:#f0e1ff ``` --- ## 2. Sequence Diagrams / Sơ đồ Tuần tự ### When to Use / Khi nào sử dụng **EN**: Use sequence diagrams for: - API communication flows - Authentication/authorization flows - Service-to-service interactions - Request/response cycles **VI**: Sử dụng sequence diagrams cho: - Luồng giao tiếp API - Luồng xác thực/phân quyền - Tương tác giữa các service - Chu kỳ request/response ### Basic Sequence Diagram ```mermaid sequenceDiagram participant Client participant API participant Service participant DB Client->>API: POST /login API->>Service: authenticate(credentials) Service->>DB: findUser(email) DB-->>Service: user Service->>Service: verifyPassword() Service-->>API: JWT token API-->>Client: 200 OK {token} ``` **Code**: ````markdown ```mermaid sequenceDiagram participant Client participant API participant Service participant DB Client->>API: POST /login API->>Service: authenticate(credentials) Service->>DB: findUser(email) DB-->>Service: user Service->>Service: verifyPassword() Service-->>API: JWT token API-->>Client: 200 OK {token} ``` ```` ### Advanced with Alt/Opt/Loop ```mermaid sequenceDiagram participant Client participant API participant Cache participant DB Client->>API: GET /users/:id API->>Cache: get(key) alt Cache Hit Cache-->>API: cached data API-->>Client: 200 OK (from cache) else Cache Miss Cache-->>API: null API->>DB: SELECT * FROM users DB-->>API: user data API->>Cache: set(key, data, ttl) API-->>Client: 200 OK (from DB) end ``` --- ## 3. Class Diagrams / Sơ đồ Class ### When to Use / Khi nào sử dụng **EN**: Use class diagrams for: - Design patterns and code structure - Object-oriented architecture - Inheritance and relationships - Module dependencies **VI**: Sử dụng class diagrams cho: - Design patterns và cấu trúc code - Kiến trúc hướng đối tượng - Kế thừa và mối quan hệ - Dependencies giữa các module ### Basic Class Diagram ```mermaid classDiagram class BaseRepository { #prisma: PrismaClient #modelName: string +findById(id: string) T +findAll(options: QueryOptions) T[] +create(data: CreateDto) T +update(id: string, data: UpdateDto) T +delete(id: string) void } class UserRepository { +findByEmail(email: string) User +findByUsername(username: string) User } class FeatureRepository { +findByName(name: string) Feature +toggleStatus(id: string) Feature } BaseRepository <|-- UserRepository BaseRepository <|-- FeatureRepository ``` --- ## 4. Graph Diagrams / Sơ đồ Graph ### When to Use / Khi nào sử dụng **EN**: Use graph diagrams for: - System architecture overview - Component relationships - Data flow diagrams - Dependency graphs **VI**: Sử dụng graph diagrams cho: - Tổng quan kiến trúc hệ thống - Mối quan hệ giữa các thành phần - Sơ đồ luồng dữ liệu - Đồ thị dependencies ### System Architecture ```mermaid graph TD Client[Web Client] --> Gateway[Traefik Gateway] Gateway --> Auth[Auth Service] Gateway --> IAM[IAM Service] Gateway --> User[User Service] Auth --> DB[(PostgreSQL)] IAM --> DB User --> DB Auth --> Cache[(Redis)] IAM --> Cache User --> Cache style Gateway fill:#e1f5ff style DB fill:#f0e1ff style Cache fill:#fff4e1 ``` ### Data Flow ```mermaid graph LR Input[User Input] --> Validation[Zod Validation] Validation --> Controller[Controller] Controller --> Service[Service Layer] Service --> Repository[Repository] Repository --> Prisma[Prisma ORM] Prisma --> DB[(Database)] Service --> Cache[Cache Service] Cache --> Redis[(Redis)] style Validation fill:#d4edda style Service fill:#e1f5ff style Cache fill:#fff4e1 ``` --- ## 5. ER Diagrams / Sơ đồ ER ### When to Use / Khi nào sử dụng **EN**: Use ER diagrams for: - Database schema documentation - Entity relationships - Data modeling - Prisma schema visualization **VI**: Sử dụng ER diagrams cho: - Tài liệu schema database - Mối quan hệ giữa các entity - Mô hình dữ liệu - Visualization Prisma schema ### Database Schema ```mermaid erDiagram User ||--o{ Session : has User ||--o{ RefreshToken : has User ||--o{ UserRole : has Role ||--o{ UserRole : has Role ||--o{ RolePermission : has Permission ||--o{ RolePermission : has User { string id PK string email UK string passwordHash boolean mfaEnabled datetime createdAt datetime updatedAt } Session { string id PK string userId FK string token UK string deviceId string ipAddress datetime expiresAt } Role { string id PK string name UK string description datetime createdAt } Permission { string id PK string code UK string resource string action string scope } ``` --- ## 6. Gantt Charts / Biểu đồ Gantt ### When to Use / Khi nào sử dụng **EN**: Use Gantt charts for: - Project timelines - Implementation phases - Migration schedules - Deployment plans **VI**: Sử dụng Gantt charts cho: - Timeline dự án - Các giai đoạn triển khai - Lịch trình migration - Kế hoạch deployment ### Project Timeline ```mermaid gantt title Documentation Update Project Timeline dateFormat YYYY-MM-DD section Phase 1 Analysis & Research :done, p1, 2024-01-01, 1d section Phase 2 Templates & Strategy :active, p2, 2024-01-02, 0.5d section Phase 3 High Priority Docs :p3, 2024-01-03, 2d section Phase 4 Remaining Docs :p4, 2024-01-05, 3d section Phase 5 QA & Verification :p5, 2024-01-08, 1d ``` --- ## 7. C4 Diagrams / Sơ đồ C4 ### When to Use / Khi nào sử dụng **EN**: Use C4 diagrams for: - System context (highest level) - Container diagrams (services, databases) - Component diagrams (modules within services) - Code diagrams (classes, functions) **VI**: Sử dụng C4 diagrams cho: - Bối cảnh hệ thống (cấp cao nhất) - Sơ đồ container (services, databases) - Sơ đồ component (modules trong services) - Sơ đồ code (classes, functions) ### System Context ```mermaid C4Context title System Context Diagram for IAM System Person(user, "User", "System user needing authentication") Person(admin, "Admin", "System administrator") System(iam, "IAM System", "Identity and Access Management") System_Ext(email, "Email Service", "SendGrid/AWS SES") System_Ext(oauth, "OAuth Providers", "Google, Facebook, GitHub") Rel(user, iam, "Authenticates with", "HTTPS") Rel(admin, iam, "Manages users and permissions", "HTTPS") Rel(iam, email, "Sends emails", "SMTP/API") Rel(iam, oauth, "OAuth login", "OAuth 2.0") ``` --- ## Styling Tips / Mẹo Styling ### Color Palette / Bảng màu ```mermaid graph LR A["Primary
#4A90E2"] --> B["Data/Cache
#F5A623"] B --> C["Success
#50E3C2"] C --> D["Warning
#F39C12"] D --> E["Error
#E74C3C"] E --> F["Processing
#9013FE"] F --> G["Info
#7B68EE"] G --> H["Neutral
#95A5A6"] style A fill:#4A90E2 style B fill:#F5A623 style C fill:#50E3C2 style D fill:#F39C12 style E fill:#E74C3C style F fill:#9013FE style G fill:#7B68EE style H fill:#95A5A6 ``` ### Style Syntax ```markdown style NodeId fill:#colorcode,stroke:#bordercolor,stroke-width:2px ``` **Examples**: ```markdown style Start fill:#e1f5ff style Error fill:#f8d7da style Process fill:#d4edda,stroke:#28a745,stroke-width:2px ``` --- ## Best Practices / Thực hành Tốt nhất ### EN: Guidelines 1. **Keep it Simple**: Don't overcomplicate diagrams 2. **Use Consistent Styling**: Apply color scheme consistently 3. **Add Legends**: Explain symbols and colors when needed 4. **Limit Complexity**: Break into multiple diagrams if too complex 5. **Test Rendering**: Always test diagrams render correctly ### VI: Hướng dẫn 1. **Giữ đơn giản**: Đừng làm phức tạp sơ đồ quá mức 2. **Sử dụng Styling nhất quán**: Áp dụng bảng màu nhất quán 3. **Thêm Chú giải**: Giải thích ký hiệu và màu sắc khi cần 4. **Giới hạn Độ phức tạp**: Chia thành nhiều sơ đồ nếu quá phức tạp 5. **Test Rendering**: Luôn test sơ đồ render chính xác --- ## Cạm bẫy Thường gặp ### ❌ Too Complex ```mermaid graph TD A --> B A --> C B --> D B --> E C --> F C --> G D --> H E --> H F --> I G --> I H --> J I --> J ``` ### ✅ Simplified with Subgraphs ```mermaid graph TD A[Start] --> B[Process A] B --> C[Process B] subgraph "Detailed Processing" C --> D[Step 1] D --> E[Step 2] end E --> F[End] ``` --- ## Kiểm tra Sơ đồ **EN**: Always test your diagrams before committing: **VI**: Luôn test sơ đồ trước khi commit: ```bash # Install mermaid-cli npm install -g @mermaid-js/mermaid-cli # Test render mmdc -i your-doc.md -o test-output.svg # Check for errors echo $? # Should be 0 if successful ``` --- ## Resources / Tài nguyên - [Mermaid Official Documentation](https://mermaid.js.org/) - Complete reference - [Mermaid Live Editor](https://mermaid.live/) - Test diagrams online - [Mermaid CheatSheet](https://jojozhuang.github.io/tutorial/mermaid-cheat-sheet/) - Quick reference --- **Tác giả**: VelikHo (hongochai10@icloud.com)