Proxy
TypeScriptApplicationProxy in TypeScript
Wraps a remote product catalog with a caching proxy that preserves the catalog interface while controlling and optimizing access to product data.
TypeScript
type Product = {
id: string;
name: string;
priceInCents: number;
};
interface ProductCatalog {
getProduct(productId: string): Promise<Product>;
}
class RemoteProductCatalog implements ProductCatalog {
async getProduct(productId: string): Promise<Product> {
console.log(`Loading ${productId} from the remote catalog`);
return {
id: productId,
name: "Mechanical Keyboard",
priceInCents: 12_999,
};
}
}
class CachedProductCatalogProxy implements ProductCatalog {
private readonly cache = new Map<string, Product>();
constructor(private readonly catalog: ProductCatalog) {}
async getProduct(productId: string): Promise<Product> {
const cached = this.cache.get(productId);
if (cached) {
return cached;
}
const product = await this.catalog.getProduct(productId);
this.cache.set(productId, product);
return product;
}
}
const catalog: ProductCatalog = new CachedProductCatalogProxy(
new RemoteProductCatalog(),
);
void catalog.getProduct("keyboard-1");
void catalog.getProduct("keyboard-1");