Proxy: a stand-in with the same face

  • Lesson 15 of 32
  • 10 min
  • Intermediate
  • 11 steps

An app that reads a huge catalog at startup, even though it hardly ever uses it. You will put an object with the same interface in front of it that decides when to create it and who may touch it.

The file is read
—
AppLazyCatalogGuardedCatalognew Proxyreactive()CatalogProxyLazyCatalogFileCatalogsettingsstateRemoteCatalogFileCatalogCataloginterfaceCatalogviewerLoggedCatalogLoggedCatalogcomponent Acomponent BAPIAPIreads the whole fileWhen the app starts▸const catalog = new FileCatalog();// the constructor reads the whole fileshowHome(); // and home never uses itthe same contractOne contract, two classesinterface Catalog {find(id: string): Product;update(p: Product): void;}// FileCatalog reads the file// LazyCatalog stands in frontFileCatalog: not yetLazyCatalogclass LazyCatalog implements Catalog {private real?: FileCatalog;find(id: string) {▸this.real ??= new FileCatalog();return this.real.find(id);}// update(p) delegates the same way}created here, oncefind() delegatesWhat the app writesconst catalog: Catalog =new LazyCatalog(); // no read yet▸catalog.find("p1"); // creates, readscatalog.find("p2"); // reusesError: admin onlyadmin gets inGuardedCatalogclass GuardedCatalog implements Catalog {// real and role come in the constructorupdate(p: Product) {▸if (this.role !== "admin")throw new Error("admin only");this.real.update(p);}}set trapread-onlyJavaScript Proxyconst asViewer = new Proxy(settings, {▸set(obj, key, value) {if (role !== "admin")throw new Error("read-only");return Reflect.set(obj, key, value);},});asViewer.theme = "light"; // Errorset: notifiesrepaintsVue 3import { reactive } from "vue";▸const state = reactive({ count: 0 });state.count; // get: records the readerstate.count++; // set: notifies themcontrols accessadds a logSame shape, different intentsame interfacebothwrap another objectbothProxycontrols accessDecoratoradds behavioura plain classThree wrong ideas“it is a network thing”it lives in your code too“it needs JS Proxy”a class is enough“it costs nothing”every call takes one more hopevery find() goes over the networkWhat you do not see▸const p = catalog.find("p1");// looks like an in-memory read// but every call goes over the networkcatalog === realCatalog; // falsecontrols accessProxy in one tableproblemcontrol access to an objectsolutionanother object, same interfaceusescreate on use, permissions, Vuevs Decoratorsame shape, different intentdon't use itwhen it hides costs
  • request
  • response
  • failed request
  • event
  • slow request

Step 1 of 11

Problem

The app creates everything, used or not

A shop has a FileCatalog: when it is created, it reads the whole product file from disk. The app creates it at startup with new FileCatalog() so it is ready.

The problem: many screens, like the home page, never look up a product. The app pays for reading the file on every startup, even if nobody ends up using the catalog.

Step 2 of 11

Concept

A contract both of them share

Whoever uses the catalog does not need to know which class is in front of them: the Catalog interface, with find and update, is enough.

A proxy is another object that implements that same interface and stands in front of the real one. The caller cannot tell the difference; the proxy decides what happens before reaching the real object: creating it, checking permissions or watching changes.

Step 3 of 11

Solution

`LazyCatalog` creates the real one when needed

LazyCatalog implements Catalog, but reads nothing when created: it only keeps an empty real field.

The first time someone calls find, it creates the FileCatalog with ??= and passes the call on. update does the same. Creating the catalog at startup no longer reads the file.

What changed

  • LazyCatalog
  • the read moves to the first find

Step 4 of 11

Technique

The first call creates, the rest reuse

The app calls catalog.find("p1"). The proxy sees that real is empty, creates the FileCatalog, passes the call on and returns the answer.

On find("p2") the field already holds the object and the proxy delegates straight away. The file is read only once, and only if someone looks up a product.

Step 5 of 11

Solution

`GuardedCatalog` decides who changes prices

Another use: in the shop’s back office, an admin can change prices and a viewer can only look. Instead of repeating the role if on every screen, a proxy holds it.

GuardedCatalog receives the real catalog and the role. find goes straight through; update throws an error if the role is not admin. Screens still use a Catalog and do not know there is a check.

What changed

  • GuardedCatalog
  • the role if on every screen

Step 6 of 11

Technique

JavaScript ships with `Proxy`

JavaScript has a Proxy object: new Proxy(object, handler) returns a wrapper, and the handler defines traps that intercept operations such as reading (get) or writing (set) a property.

Here there is only a set trap: reading asViewer.theme reaches settings directly, but writing throws an error if role is not admin. It is the same permission proxy, without writing a class.

Step 7 of 11

Technique

Vue uses proxies to know what to repaint

In Vue 3, reactive() returns a proxy of the object. When a component reads state.count, the get trap records that this component depends on count.

When your code writes state.count++, the set trap notifies whoever read it, and Vue repaints them. You write a plain object; the proxy keeps track.

Step 8 of 11

Trade-off

Same shape, different intent

Think of a LoggedCatalog that wraps the catalog and writes a log on every call: it is a Decorator, as you saw in its lesson. In code it looks a lot like LazyCatalog: both implement Catalog and call the object they wrap.

The difference is intent. A Decorator adds behaviour; a Proxy controls access to the real one: when it is created, who gets in, which changes are watched. A cache can be either: name it after what you are after.

Step 9 of 11

Concept

Three wrong ideas about Proxy

In networking, a proxy is a server in the middle. The pattern uses the same idea inside your code: any object that stands in front of another with the same interface.

You do not need the JavaScript Proxy: LazyCatalog is a plain class. And it is not free: every call that goes through the proxy takes one more hop.

Step 10 of 11

Trade-off

When a proxy hides too much

If find looks like an in-memory read but the proxy goes over the network, the caller does not expect the delay or the network errors. The same interface hides a cost that was worth seeing.

Identity changes too: the proxy is another object, so comparing it with === against the real one gives false, and debugging has one more hop. Do not use one if the caller needs to know what happens, or in a loop where every extra access weighs.

Step 11 of 11

Summary

A stand-in with the same face

A proxy implements the same interface as the real object and controls access to it: it creates it on first use, checks permissions or watches changes, like reactive() in Vue.

In code it looks like a Decorator; the difference is intent. If it hides costs the caller should see, do not use one.

You will learn

  • Spot when a stand-in helps: create an expensive object late or control who uses it.
  • Write a proxy that creates the real object only when someone needs it.
  • Use a proxy to check permissions without changing the caller.
  • Recognise the JavaScript `Proxy` and how Vue uses it for reactivity.
  • Tell Proxy from Decorator and know when a proxy hides too much.