← Back to scenarios
ScenarioCatalog DB

Access control proxy

Check permissions before allowing operations on a sensitive resource.

Problem

A system must enforce authorization before delegating sensitive operations to a protected resource while preserving the resource's interface for authorized clients.

Related patterns

Implementations

Proxy

TypeScriptApplication

Proxy 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");

Associated technologies