15 KiB
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 (e.g., "Onboarding process")
- Decision trees and conditional logic (e.g., "Discount calculation")
- Process flows with multiple branches (e.g., "Order fulfillment")
- Troubleshooting procedures (e.g., "Login issue diagnosis")
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
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
Explanation: A basic flowchart starting with an input, followed by a validation check. If valid, it proceeds to processing and returns a result; otherwise, it shows an error and ends.
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:#e1f5ff
style End fill:#d4edda
style Check fill:#fff3cd
style Error fill:#f8d7da
```
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
Explanation: A flowchart featuring an authorization check and a dedicated Subgraph for detailed request processing steps.
2. Sequence Diagrams / Sơ đồ Tuần tự
When to Use / Khi nào sử dụng
EN: Use sequence diagrams for:
- API communication flows (e.g., "New order creation API")
- Authentication/authorization flows (e.g., "OAuth2 login flow")
- Service-to-service interactions (e.g., "Microservices sync/async calls")
- Request/response cycles (e.g., "Checkout process")
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
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}
Explanation: A login sequence illustrating the interaction between the Client, API, Service Layer, and Database, including password verification.
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
Explanation: A data retrieval sequence using Alt/Else blocks to handle both Cache Hit and Cache Miss scenarios.
3. Class Diagrams / Sơ đồ Class
When to Use / Khi nào sử dụng
EN: Use class diagrams for:
- Design patterns and code structure (e.g., "Singleton Pattern for Logger")
- Object-oriented architecture (e.g., "Domain-Driven Design (DDD) models")
- Inheritance and relationships (e.g., "Repository base and concrete classes")
- Module dependencies (e.g., "Service layer 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
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
Explanation: A class diagram showing inheritance relationships between a generic BaseRepository and specific repository implementations.
4. Graph Diagrams / Sơ đồ Graph
When to Use / Khi nào sử dụng
EN: Use graph diagrams for:
- System architecture overview (e.g., "Microservices Architecture")
- Component relationships (e.g., "Service-to-database mapping")
- Data flow diagrams (e.g., "Request processing pipeline")
- Dependency graphs (e.g., "Package to package dependencies")
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
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
User --> Cache
style Gateway fill:#2980b9,stroke:#333,stroke-width:2px,color:#fff
style Auth fill:#8e44ad,stroke:#333,stroke-width:2px,color:#fff
style IAM fill:#8e44ad,stroke:#333,stroke-width:2px,color:#fff
style User fill:#8e44ad,stroke:#333,stroke-width:2px,color:#fff
style DB fill:#f39c12,stroke:#333,stroke-width:2px,color:#fff
style Cache fill:#f39c12,stroke:#333,stroke-width:2px,color:#fff
Explanation: A high-level view of the system architecture showing how the Gateway routes requests to different services, all connected to a shared Database and 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)]
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
Explanation: A detailed data flow showing Input going through Validation -> Controller -> Service -> Repository -> ORM -> DB, while also interacting with the Cache.
5. ER Diagrams / Sơ đồ ER
When to Use / Khi nào sử dụng
EN: Use ER diagrams for:
- Database schema documentation (e.g., "User and IAM tables")
- Entity relationships (e.g., "One-to-many between User and Sessions")
- Data modeling (e.g., "Designing new feature entities")
- Prisma schema visualization (e.g., "Mapping code entities to DB tables")
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
}
Explanation: An Entity-Relationship diagram illustrating a typical IAM schema with Users, Sessions, Roles, and Permissions.
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
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")
Styling Tips / Mẹo Styling
Color Palette / Bảng màu
graph LR
A["Primary<br/>#e1f5ff"] --> B["Secondary<br/>#fff4e1"]
B --> C["Success<br/>#d4edda"]
C --> D["Warning<br/>#fff3cd"]
D --> E["Error<br/>#f8d7da"]
E --> F["Info<br/>#f0e1ff"]
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
Explanation: The recommended color palette for consistent diagram styling within the project.
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 / Best Practices
EN: Guidelines
- Keep it Simple: Don't overcomplicate diagrams
- Use Consistent Styling: Apply color scheme consistently
- Add Legends: Explain symbols and colors when needed
- Limit Complexity: Break into multiple diagrams if too complex
- Test Rendering: Always test diagrams render correctly
VI: Hướng dẫn
- Giữ đơn giản: Đừng làm phức tạp sơ đồ quá mức
- Sử dụng Styling nhất quán: Áp dụng bảng màu nhất quán
- Thêm Chú giải: Giải thích ký hiệu và màu sắc khi cần
- Giới hạn Độ phức tạp: Chia thành nhiều sơ đồ nếu quá phức tạp
- Test Rendering: Luôn test sơ đồ render chính xác
Common Pitfalls / Lỗi 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]
Testing Diagrams / Test 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 high-quality PNG with black background
mmdc -i your-doc.md -o test-output.png -b black -t dark -s 3
# Render ALL diagrams in a markdown file
mmdc -i your-doc.md
# Parameter Explanations:
# -i: Input file (.md or .mmd)
# -o: Output file (format based on extension .svg, .png, .pdf)
# -b: Background color (hex code or color names like black, white, transparent)
# -t: Theme (default, forest, dark, neutral)
# -s: Scale (increase resolution, e.g., 3 for sharper images)
Resources / Tài nguyên
- Mermaid Official Documentation - Complete reference
- Mermaid Live Editor - Test diagrams online
- Mermaid CheatSheet - Quick reference
Last Updated: 2026-01-05