Files
pos-system/docs/en/templates/skill-pattern.md

476 lines
13 KiB
Markdown

# [Pattern Name] Pattern / Pattern [Tên Pattern]
> **EN**: Brief English description of when and why to use this pattern
> **VI**: Mô tả ngắn gọn bằng tiếng Việt về khi nào và tại sao sử dụng pattern này
## Pattern Overview / Tổng quan Pattern
```mermaid
graph LR
Input[Input/Request] --> Process[Pattern Process]
Process --> Output[Output/Result]
subgraph Pattern["Pattern Implementation"]
Process --> Step1[Step 1]
Step1 --> Step2[Step 2]
Step2 --> Step3[Step 3]
end
style Input fill:#e1f5ff
style Output fill:#d4edda
style Pattern fill:#f0e1ff
```
## When to Use / Khi nào sử dụng
### EN: Use this pattern when
- Scenario 1: Description of when this pattern is beneficial
- Scenario 2: Another use case
- Scenario 3: Additional context
**DO use this pattern for**:
- ✅ Use case 1
- ✅ Use case 2
**DON'T use this pattern for**:
- ❌ Anti-pattern 1
- ❌ Anti-pattern 2
### VI: Sử dụng pattern này khi
- Tình huống 1: Mô tả khi pattern này có lợi
- Tình huống 2: Trường hợp sử dụng khác
- Tình huống 3: Bối cảnh bổ sung
**NÊN sử dụng pattern này cho**:
- ✅ Trường hợp 1
- ✅ Trường hợp 2
**KHÔNG NÊN sử dụng pattern này cho**:
- ❌ Anti-pattern 1
- ❌ Anti-pattern 2
## Core Concepts / Khái niệm Cốt lõi
### EN: Key Principles
1. **Principle 1**: Description of the first core principle
2. **Principle 2**: Description of the second core principle
3. **Principle 3**: Description of the third core principle
### VI: Nguyên tắc Chính
1. **Nguyên tắc 1**: Mô tả nguyên tắc cốt lõi đầu tiên
2. **Nguyên tắc 2**: Mô tả nguyên tắc cốt lõi thứ hai
3. **Nguyên tắc 3**: Mô tả nguyên tắc cốt lõi thứ ba
## Implementation / Triển khai
### Basic Implementation / Triển khai Cơ bản
**EN**: Step-by-step explanation of how to implement this pattern.
**VI**: Giải thích từng bước về cách triển khai pattern này.
```typescript
// EN: Basic implementation example
// VI: Ví dụ triển khai cơ bản
/**
* EN: Pattern implementation class
* VI: Class triển khai pattern
*/
export class ExamplePattern {
/**
* EN: Constructor with dependencies
* VI: Constructor với các dependencies
*/
constructor(
private dependency1: Dependency1,
private dependency2: Dependency2
) {}
/**
* EN: Core method implementing the pattern
* VI: Phương thức cốt lõi triển khai pattern
*
* @param input - EN: Input data / VI: Dữ liệu đầu vào
* @returns EN: Processed result / VI: Kết quả đã xử lý
*/
async execute(input: InputType): Promise<OutputType> {
// EN: Step 1: Validate input
// VI: Bước 1: Validate đầu vào
this.validateInput(input);
// EN: Step 2: Process
// VI: Bước 2: Xử lý
const processed = await this.process(input);
// EN: Step 3: Return result
// VI: Bước 3: Trả về kết quả
return this.formatOutput(processed);
}
private validateInput(input: InputType): void {
// EN: Validation logic
// VI: Logic validation
if (!input) {
throw new Error('Input is required / Đầu vào là bắt buộc');
}
}
private async process(input: InputType): Promise<ProcessedType> {
// EN: Core business logic
// VI: Logic nghiệp vụ cốt lõi
return await this.dependency1.transform(input);
}
private formatOutput(processed: ProcessedType): OutputType {
// EN: Format for output
// VI: Định dạng cho đầu ra
return {
success: true,
data: processed,
};
}
}
```
**File Location / Vị trí File**:
- **Template**: [`_template/src/modules/example/example.pattern.ts`](file:///Users/velikho/Desktop/WORKING/Base/services/_template/src/modules/example/example.pattern.ts)
- **Production**: [`iam-service/src/modules/example/example.pattern.ts`](file:///Users/velikho/Desktop/WORKING/Base/services/iam-service/src/modules/example/example.pattern.ts)
### Advanced Implementation / Triển khai Nâng cao
**EN**: More complex implementation with additional features.
**VI**: Triển khai phức tạp hơn với các tính năng bổ sung.
```typescript
// EN: Advanced implementation with caching and error handling
// VI: Triển khai nâng cao với caching và xử lý lỗi
export class AdvancedExamplePattern extends ExamplePattern {
constructor(
dependency1: Dependency1,
dependency2: Dependency2,
private cache: CacheService,
private logger: Logger
) {
super(dependency1, dependency2);
}
async execute(input: InputType): Promise<OutputType> {
// EN: Try cache first
// VI: Thử cache trước
const cacheKey = this.getCacheKey(input);
const cached = await this.cache.get<OutputType>(cacheKey);
if (cached) {
this.logger.info('Cache hit', { key: cacheKey });
return cached;
}
try {
// EN: Execute pattern logic
// VI: Thực thi logic pattern
const result = await super.execute(input);
// EN: Cache result
// VI: Cache kết quả
await this.cache.set(cacheKey, result, 300); // 5 minutes
return result;
} catch (error) {
// EN: Error handling
// VI: Xử lý lỗi
this.logger.error('Pattern execution failed', { error, input });
throw new PatternExecutionError('Execution failed', { cause: error });
}
}
private getCacheKey(input: InputType): string {
return `pattern:example:${JSON.stringify(input)}`;
}
}
```
## Pattern Diagram / Sơ đồ Pattern
### Class Structure / Cấu trúc Class
```mermaid
classDiagram
class ExamplePattern {
-dependency1: Dependency1
-dependency2: Dependency2
+execute(input: InputType): OutputType
-validateInput(input: InputType): void
-process(input: InputType): ProcessedType
-formatOutput(processed: ProcessedType): OutputType
}
class AdvancedExamplePattern {
-cache: CacheService
-logger: Logger
+execute(input: InputType): OutputType
-getCacheKey(input: InputType): string
}
class Dependency1 {
+transform(input: InputType): ProcessedType
}
class CacheService {
+get(key: string): Promise~any~
+set(key: string, value: any, ttl: number): Promise~void~
}
ExamplePattern <|-- AdvancedExamplePattern
ExamplePattern --> Dependency1
AdvancedExamplePattern --> CacheService
```
### Sequence Flow / Luồng Tuần tự
```mermaid
sequenceDiagram
participant Client
participant Pattern as ExamplePattern
participant Dep1 as Dependency1
participant Cache as CacheService
Client->>Pattern: execute(input)
Pattern->>Cache: get(cacheKey)
Cache-->>Pattern: null (cache miss)
Pattern->>Pattern: validateInput(input)
Pattern->>Dep1: transform(input)
Dep1-->>Pattern: processed
Pattern->>Pattern: formatOutput(processed)
Pattern->>Cache: set(cacheKey, result, ttl)
Cache-->>Pattern: void
Pattern-->>Client: result
```
## Usage Examples / Ví dụ Sử dụng
### Example 1 / Ví dụ 1: Basic Usage
**EN**: Basic usage scenario with explanation.
**VI**: Tình huống sử dụng cơ bản với giải thích.
```typescript
// EN: Setup
// VI: Thiết lập
const dependency1 = new Dependency1();
const dependency2 = new Dependency2();
const pattern = new ExamplePattern(dependency1, dependency2);
// EN: Execute pattern
// VI: Thực thi pattern
const input: InputType = {
id: '123',
data: 'example',
};
const result = await pattern.execute(input);
console.log(result);
// EN: Output / VI: Kết quả:
// { success: true, data: { ... } }
```
### Example 2 / Ví dụ 2: Advanced Usage with Caching
**EN**: Advanced usage with caching enabled.
**VI**: Sử dụng nâng cao với caching được bật.
```typescript
// EN: Setup with additional dependencies
// VI: Thiết lập với các dependencies bổ sung
const cache = new CacheService();
const logger = new Logger();
const pattern = new AdvancedExamplePattern(
dependency1,
dependency2,
cache,
logger
);
// EN: First call (cache miss)
// VI: Lần gọi đầu tiên (cache miss)
const result1 = await pattern.execute(input);
// EN: Second call (cache hit)
// VI: Lần gọi thứ hai (cache hit)
const result2 = await pattern.execute(input); // Returns cached result
```
## Best Practices / Best Practices
### EN: Recommended Practices
1. **Practice 1**: Description of best practice with reasoning
2. **Practice 2**: Another important guideline
3. **Practice 3**: Additional recommendation
**Configuration / Cấu hình**:
```typescript
const config = {
timeout: 5000,
retries: 3,
cacheTime: 300, // 5 minutes
};
```
### VI: Thực hành Được đề xuất
1. **Nguyên tắc 1**: Mô tả best practice với lý do
2. **Nguyên tắc 2**: Hướng dẫn quan trọng khác
3. **Nguyên tắc 3**: Khuyến nghị bổ sung
## Common Mistakes / Lỗi Thường gặp
### EN: Mistakes to Avoid
#### Mistake 1 / Lỗi 1: [Description]
```typescript
// ❌ BAD: Incorrect implementation
const result = await pattern.execute(null); // Will throw error
```
```typescript
// ✅ GOOD: Correct implementation
if (input) {
const result = await pattern.execute(input);
}
```
**EN Why**: Explanation of why the first approach is bad and the second is good.
**VI Tại sao**: Giải thích tại sao cách tiếp cận đầu tiên là không tốt và cách thứ hai là tốt.
#### Mistake 2 / Lỗi 2: [Description]
(Repeat pattern for each common mistake)
## Performance Considerations / Cân nhắc Hiệu suất
**EN**: Performance characteristics and optimization tips.
**VI**: Đặc điểm hiệu suất và mẹo tối ưu hóa.
| Aspect / Khía cạnh | Impact / Tác động | Mitigation / Giảm thiểu |
|---------------------|-------------------|-------------------------|
| Memory usage / Sử dụng RAM | Medium / Trung bình | Use caching strategically / Sử dụng caching có chiến lược |
| CPU usage / Sử dụng CPU | Low / Thấp | N/A |
| I/O operations / Thao tác I/O | High / Cao | Implement connection pooling / Triển khai connection pooling |
## Testing / Kiểm thử
### Unit Test Example / Ví dụ Unit Test
```typescript
// EN: Unit test for the pattern
// VI: Unit test cho pattern
describe('ExamplePattern', () => {
let pattern: ExamplePattern;
let mockDep1: jest.Mocked<Dependency1>;
let mockDep2: jest.Mocked<Dependency2>;
beforeEach(() => {
mockDep1 = {
transform: jest.fn(),
} as any;
mockDep2 = {} as any;
pattern = new ExamplePattern(mockDep1, mockDep2);
});
it('should execute successfully', async () => {
// EN: Arrange
// VI: Chuẩn bị
const input = { id: '123', data: 'test' };
const expectedProcessed = { transformed: true };
mockDep1.transform.mockResolvedValue(expectedProcessed);
// EN: Act
// VI: Thực thi
const result = await pattern.execute(input);
// EN: Assert
// VI: Kiểm tra
expect(result.success).toBe(true);
expect(result.data).toEqual(expectedProcessed);
expect(mockDep1.transform).toHaveBeenCalledWith(input);
});
it('should throw error for invalid input', async () => {
// EN: Expect error for null input
// VI: Mong đợi lỗi cho đầu vào null
await expect(pattern.execute(null as any))
.rejects
.toThrow('Input is required');
});
});
```
## Related Patterns / Patterns Liên quan
**EN**: Other patterns that complement or relate to this one.
**VI**: Các patterns khác bổ sung hoặc liên quan đến pattern này.
- [Related Pattern 1](./related-pattern-1.md) - EN: How it relates / VI: Cách nó liên quan
- [Related Pattern 2](./related-pattern-2.md) - EN: Comparison / VI: So sánh
- [Alternative Pattern](./alternative-pattern.md) - EN: When to use instead / VI: Khi nào sử dụng thay thế
## Real-World Examples / Ví dụ Thực tế
**EN**: Examples of this pattern used in the codebase.
**VI**: Ví dụ về pattern này được sử dụng trong codebase.
### Example from IAM Service
**File**: [`iam-service/src/modules/rbac/rbac.service.ts`](file:///Users/velikho/Desktop/WORKING/Base/services/iam-service/src/modules/rbac/rbac.service.ts)
```typescript
// EN: Real implementation from IAM service
// VI: Triển khai thực tế từ IAM service
export class RBACService implements ExamplePattern {
// ... implementation
}
```
## Additional Resources / Tài nguyên Bổ sung
### EN: Related Documentation
- [API Design Guide](../api-design.md) - How this pattern fits into API design
- [Error Handling](../error-handling-patterns.md) - Error handling for this pattern
- [Testing Guide](../testing-patterns.md) - Testing strategies
### VI: Tài liệu Liên quan
- [Hướng dẫn Thiết kế API](../api-design.md) - Pattern này khớp với thiết kế API như thế nào
- [Xử lý Lỗi](../error-handling-patterns.md) - Xử lý lỗi cho pattern này
- [Hướng dẫn Kiểm thử](../testing-patterns.md) - Chiến lược kiểm thử
### External Resources / Tài nguyên Bên ngoài
- [Design Patterns Book](https://example.com) - Classic reference
- [Blog Post](https://example.com) - Modern interpretation
---
**Last Updated / Cập nhật lần cuối**: YYYY-MM-DD
**Complexity / Độ phức tạp**: Beginner/Intermediate/Advanced
**Category / Danh mục**: [Category Name]
**Authors / Tác giả**: Your Name