Proxy cung cấp surrogate object thay thế cho object khác — control access đến object gốc và có thể thêm logic trước/sau.
Các loại phổ biến:
- Virtual Proxy (lazy initialization): chỉ tạo object nặng khi thực sự cần — ví dụ lazy load image;
- Protection Proxy (access control): kiểm tra permission trước khi delegate;
- Caching Proxy: cache result của expensive operation;
- Logging Proxy: ghi log mọi request đến object
JavaScript Proxy object là triển khai native:
javascript
const handler = {
get(obj, prop) {
console.log(`Getting ${String(prop)}`)
return obj[prop]
}
}
const proxy = new Proxy(target, handler)Trong NestJS, Guards và Interceptors là Proxy pattern.
- Khác Decorator: Proxy thường quản lý lifecycle của subject; Decorator thêm behavior mà client biết.
- Dùng khi: cần access control, lazy init, caching, logging mà không sửa class gốc.
Proxy provides a surrogate object that acts on behalf of another object — controlling access to the original and optionally adding logic before or after.
Common types:
- Virtual Proxy (lazy initialization): creates a heavy object only when truly needed — e.g., lazy-loading an image;
- Protection Proxy (access control): checks permissions before delegating;
- Caching Proxy: caches the result of expensive operations;
- Logging Proxy: records every request to the object
JavaScript's native Proxy object is an implementation of this:
javascript
const handler = {
get(obj, prop) {
console.log(`Getting ${String(prop)}`)
return obj[prop]
}
}
const proxy = new Proxy(target, handler)In NestJS, Guards and Interceptors are the Proxy pattern.
- Difference from Decorator: Proxy typically manages the subject's lifecycle; Decorator adds behavior that the client is aware of.
- Use it when you need access control, lazy initialization, caching, or logging without modifying the original class.