patterntypescriptTip
Proxy Pattern: Control Access to an Object
Viewed 0 times
proxy patternstructural patterncaching proxyaccess controllazy loadingvirtual proxy
Problem
You need to add access control, lazy loading, logging, or caching around a real object without changing its interface or modifying its code.
Solution
Create a proxy class implementing the same interface as the real object. The proxy intercepts calls, applies its additional behavior, then delegates to the real object when appropriate.
interface Service {
request(endpoint: string): Promise<unknown>;
}
class RealService implements Service {
async request(endpoint: string) {
const res = await fetch(endpoint);
return res.json();
}
}
class CachingProxy implements Service {
private cache = new Map<string, unknown>();
constructor(private real: RealService) {}
async request(endpoint: string): Promise<unknown> {
if (this.cache.has(endpoint)) {
console.log('Cache hit:', endpoint);
return this.cache.get(endpoint);
}
const result = await this.real.request(endpoint);
this.cache.set(endpoint, result);
return result;
}
}
const service: Service = new CachingProxy(new RealService());
await service.request('/api/users'); // fetches
await service.request('/api/users'); // returns cachedWhy
The proxy pattern is the mechanism behind many framework features: ORM lazy loading, Vue/Immer reactive proxies, API access guards. It intercepts without modifying the target.
Gotchas
- JavaScript's built-in
Proxyobject is a powerful but different mechanism — the pattern and the language feature serve the same purpose but operate differently. - Virtual proxies (lazy loading) must be transparent — callers must not be able to distinguish proxy from real object.
- Proxies add indirection. For hot-path code, benchmark the overhead before applying.
Revisions (0)
No revisions yet.