-2

Hướng dẫn sơ đồ Mermaid

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 (ví dụ: Quy trình đăng ký tài khoản)
  • Cây quyết định và logic điều kiện (ví dụ: Luồng phê duyệt đơn hàng)
  • Luồng quy trình với nhiều nhánh (ví dụ: Xử lý thanh toán đa kênh)
  • Thủ tục khắc phục sự cố (ví dụ: Các bước debug lỗi server)

Basic Flowchart

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:#2980b9,stroke:#333,stroke-width:2px,color:#fff
    style End fill:#27ae60,stroke:#333,stroke-width:2px,color:#fff
    style Check fill:#f39c12,stroke:#333,stroke-width:2px,color:#fff
    style Error fill:#c0392b,stroke:#333,stroke-width:2px,color:#fff

Giải thích: Sơ đồ này minh họa quy trình từ lúc Bắt đầu -> Nhận đầu vào -> Kiểm tra tính hợp lệ -> Xử lý (nếu hợp lệ) hoặc Báo lỗi (nếu không) -> Kết thúc.

Code:

```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:#2980b9,stroke:#333,stroke-width:2px,color:#fff
    style End fill:#27ae60,stroke:#333,stroke-width:2px,color:#fff
    style Check fill:#f39c12,stroke:#333,stroke-width:2px,color:#fff
    style Error fill:#c0392b,stroke:#333,stroke-width:2px,color:#fff
```

Advanced Flowchart with Subgraphs

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

Giải thích: Sơ đồ này cho thấy quy trình xử lý request phức tạp hơn với các logic nhóm trong subgraph. Nếu Auth thất bại, trả về 401. Nếu thành công, tiếp tục xử lý, validate, chạy logic, format và trả về 200 OK.


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 (ví dụ: API tạo đơn hàng mới)
  • Luồng xác thực/phân quyền (ví dụ: Luồng đăng nhập và cấp Token)
  • Tương tác giữa các service (ví dụ: Order Service gọi Inventory Service)
  • Chu kỳ request/response (ví dụ: Xử lý Request trả về JSON)

Basic Sequence Diagram

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}

Giải thích: Sơ đồ tuần tự mô tả luồng đăng nhập: Client gửi thông tin -> API gọi Service -> Service kiểm tra DB -> DB trả về User -> Service xác thực pass -> Service trả Token -> API trả về cho Client.

Code:

```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

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

Giải thích: Sơ đồ này sử dụng khối alt để mô tả logic rẽ nhánh: Nếu có Cache (Cache Hit) thì trả về ngay. Nếu không (Cache Miss) thì query DB, lưu vào Cache rồi mới trả về.


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 (ví dụ: Singleton Pattern cho Logger)
  • Kiến trúc hướng đối tượng (ví dụ: Cấu trúc Class User và Admin)
  • Kế thừa và mối quan hệ (ví dụ: BaseRepository và UserRepository)
  • Dependencies giữa các module (ví dụ: PaymentModule phụ thuộc OrderModule)

Basic Class Diagram

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

Giải thích: Sơ đồ Class thể hiện mối quan hệ kế thừa (<|--): UserRepositoryFeatureRepository đều kế thừa từ BaseRepository, tận dụng các phương thức chung như findById, create.


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 (ví dụ: Kiến trúc Microservices)
  • Mối quan hệ giữa các thành phần (ví dụ: Web Client kết nối Gateway)
  • Sơ đồ luồng dữ liệu (ví dụ: Dữ liệu từ API xuống Database)
  • Đồ thị dependencies (ví dụ: Các gói npm phụ thuộc lẫn nhau)

System Architecture

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:#2980b9,stroke:#333,stroke-width:2px,color:#fff
    style DB fill:#8e44ad,stroke:#333,stroke-width:2px,color:#fff
    style Cache fill:#f39c12,stroke:#333,stroke-width:2px,color:#fff

Giải thích: Sơ đồ kiến trúc tổng quan: Web Client đi qua Traefik Gateway, sau đó được điều hướng đến các microservices (Auth, IAM, User). Các service này đều kết nối đến Database chung và Redis Cache.

Data Flow

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:#27ae60,stroke:#333,stroke-width:2px,color:#fff
    style Service fill:#2980b9,stroke:#333,stroke-width:2px,color:#fff
    style Cache fill:#f39c12,stroke:#333,stroke-width:2px,color:#fff

Giải thích: Sơ đồ luồng dữ liệu chi tiết: Input đi qua lớp Validation -> Controller -> Service -> Repository -> ORM -> DB. Đồng thời Service cũng tương tác với Cache.


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

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
    }

Giải thích: Sơ đồ ER mô tả quan hệ thực thể: Một User có nhiều Session, RefreshTokenUserRole. Quan hệ ||--o{ nghĩa là "một-nhiều".


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

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

Giải thích: Biểu đồ Gantt giúp theo dõi tiến độ dự án theo thời gian. Các thanh màu thể hiện trạng thái: done (đã xong), active (đang làm), hoặc chưa làm.


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

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")

Giải thích: Sơ đồ C4 Context cho thấy bối cảnh hệ thống ở mức cao nhất: Người dùng và Admin tương tác với IAM System. Hệ thống này lại tương tác với các hệ thống bên ngoài như Email ServiceOAuth Providers.


Styling Tips / Mẹo Styling

Color Palette / Bảng màu

graph LR
    A["Primary<br/>#2980B9"] --> B["Data/Cache<br/>#F39C12"]
    B --> C["Success<br/>#27AE60"]
    C --> D["Warning<br/>#E67E22"]
    D --> E["Error<br/>#C0392B"]
    E --> F["Processing<br/>#8E44AD"]
    F --> G["Info<br/>#3498DB"]
    G --> H["Neutral<br/>#7F8C8D"]
    
    style A fill:#2980B9,color:#fff
    style B fill:#F39C12,color:#fff
    style C fill:#27AE60,color:#fff
    style D fill:#E67E22,color:#fff
    style E fill:#C0392B,color:#fff
    style F fill:#8E44AD,color:#fff
    style G fill:#3498DB,color:#fff
    style H fill:#7F8C8D,color:#fff

Style Syntax

style NodeId fill:#colorcode,stroke:#bordercolor,stroke-width:2px

Examples:

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

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

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:

# Install mermaid-cli
npm install -g @mermaid-js/mermaid-cli

# Test render (SVG)
mmdc -i your-doc.md -o test-output.svg

# Render PNG chất lượng cao, nền đen
mmdc -i your-doc.md -o test-output.png -b black -t dark -s 3

# Render TOÀN BỘ sơ đồ trong file markdown
mmdc -i your-doc.md

# Giải thích các tham số:
# -i: File đầu vào (.md hoặc .mmd)
# -o: File đầu ra (định dạng dựa trên đuôi .svg, .png, .pdf)
# -b: Màu nền (hex code hoặc tên màu như black, white, transparent)
# -t: Theme (default, forest, dark, neutral)
# -s: Scale (tăng độ phân giải, ví dụ: 3 cho ảnh nét hơn)

Resources / Tài nguyên


Tác giả: VelikHo (hongochai10@icloud.com)


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí