Execution Context trong NestJS

Execution Context là một object chứa thông tin chi tiết về request hiện tại đang được xử lý. Nó được sử dụng trong Guards, Interceptors, Exception Filters, và Pipes để truy cập các thông tin như HTTP request, response, handler method, class, arguments, v.v.

Khái Niệm Execution Context

Execution Context cung cấp truy cập vào:
  • HTTP Request/Response objects (Express)
  • Handler class được gọi
  • Handler method đang thực thi
  • Arguments của method
  • Class metadata (custom decorators)
  • Execution type (HTTP, WebSocket, RPC)

ExecutionContext API

switchToHttp()

switchToWs()

switchToRpc()

getHandler() & getClass()

getArgs() & getArgByIndex()

getType()

Ví Dụ Execution Context Thực Tế

1. Request Logging with Context

2. Role-Based Authorization Guard

3. Custom Decorator with Execution Context

4. Metadata Extraction Guard

5. Dynamic Handler Execution

6. Request Validation with Context

7. Performance Monitoring with Context

8. Conditional Response Transformation

9. Multi-Type Context Handling

10. Audit Logging with Context

Execution Context in Different Contexts

HTTP Context

WebSocket Context

RPC Context

Best Practices

1. Check Execution Type Before Switching

2. Use Type Guards

3. Cache Context Information

4. Use Reflector for Metadata

5. Error Handling with Context

Complete Example

Kết Luận

Execution Context là công cụ mạnh mẽ để:
  • Truy cập thông tin về request hiện tại
  • Extract metadata từ handlers
  • Implement authorization logic
  • Log và audit operations
  • Handle multiple execution types
Sử dụng Execution Context đúng cách giúp bạn:
  • Xây dựng flexible guards và interceptors
  • Implement fine-grained access control
  • Tạo powerful audit logging
  • Handle complex authorization scenarios
  • Support multiple execution contexts (HTTP, WebSocket, RPC)
Execution Context là nền tảng của nhiều advanced NestJS patterns và features!