Proxy Pattern — Design Patterns

A proxy puts a stand-in object in front of the real object. The stand-in is used the same way, and it controls access to the real object: pass on, refuse…

You call the director's number, but the assistant answers. The assistant can answer some questions alone, when they already know the answer ("the meeting is at 3"). They can also refuse callers without an appointment, write down who called, or connect you to the director. The number stays the same, and you don't need to know there's an assistant.

The Proxy pattern puts a stand-in object in front of the real one. The stand-in is used in exactly the same way as the real object, so the caller doesn't know it's talking to a stand-in. In the picture, the assistant is the stand-in, the director is the real object, and the same number is the same way of using it. The stand-in decides: pass the call on to the real object, refuse it, give an answer it saved earlier (a cache), record who asked, or delay creating the real object until it's truly needed.

The problem: a wrong rate quietly becomes NaN

These are Kancil Courier's rates per kg, and the shipping cost function:

const RATES = { regular: 10, express: 18, sameday: 25 } // per kg

function calculateShipping(service, kg) {
  return kg * RATES[service]
}

console.log(calculateShipping("overnight", 2)) // NaN: a mistyped service, no error
RATES.express = "$18"                          // simply accepted
console.log(calculateShipping("express", 2))   // NaN

NaN means "not a number". RATES is read on the checkout page, the cost check page and the API. You want three things: services that don't exist are refused, rates that aren't numbers are refused, and every read of a rate is recorded. All of that without changing the RATES object and without changing all its callers.

JavaScript's built-in Proxy: target, handler, trap

JavaScript has a built-in Proxy feature for this. The code below makes rates, a stand-in for RATES. Then calculateShipping reads the rate through that stand-in:

const rates = new Proxy(RATES, {
  get(target, prop, receiver) {
    if (!Object.hasOwn(target, prop)) throw new Error("Unknown service: " + String(prop))
    console.log("read rate " + String(prop))
    return Reflect.get(target, prop, receiver)
  },
  set(target, prop, value, receiver) {
    if (typeof value !== "number" || value <= 0) throw new TypeError("Rate " + String(prop) + " must be a positive number")
    console.log("set rate " + String(prop) + " to " + value)
    return Reflect.set(target, prop, value, receiver)
  },
})

function calculateShipping(service, kg) {
  return kg * rates[service] // through the proxy now
}

console.log(calculateShipping("express", 2)) // read rate express, then 36
calculateShipping("overnight", 2)            // Error: Unknown service: overnight
rates.express = "$18"                        // TypeError: Rate express must be a positive number

One trap per kind of operation

Every basic operation on an object has its own trap. JavaScript has 13 traps, and the most used are:

operation trap
rates.express get
rates.express = 20 set
"express" in rates has
delete rates.express deleteProperty
Object.keys(rates) ownKeys
fn(...), when the target is a function apply
new Fn(...), when the target is a class construct

Take a guess first. The rates handler above only has a get trap and a set trap. The get trap prints read rate ... each time a rate is read. How many read rate lines appear when the code runs "express" in rates (which checks whether an express property exists)?

0 read rate lines. "express" in rates uses the has trap, not get. An operation whose trap isn't written in the handler goes straight to the target, so in reaches RATES and gives true with no log. "overnight" in rates also just gives false, with no error, because the service check is in get.

A cache through the apply trap

If rates are fetched from a server, every read is a request. A proxy with an apply trap in front of the fetching function can remember the answers. The apply trap runs every time that function is called:

let request = 0
function fetchRate(service) {
  request++
  console.log("GET /rates/" + service)
  return { regular: 10, express: 18, sameday: 25 }[service]
}

const cache = new Map()
const fetchRateCached = new Proxy(fetchRate, {
  apply(target, thisArg, args) {
    const service = args[0]
    if (!cache.has(service)) cache.set(service, Reflect.apply(target, thisArg, args))
    return cache.get(service)
  },
})

fetchRateCached("express")
fetchRateCached("express")
fetchRateCached("regular")
console.log("request: " + request) // request: 2

Three calls, two requests: the second express is answered from cache. The caller still writes fetchRateCached("express"), like calling a plain function.

A proxy without the Proxy API: lazy loading

The pattern is older than the built-in Proxy feature (the Proxy API). A plain object with the same methods can be a stand-in too. The most common example is a virtual proxy. With it, a real object that is expensive (slow or heavy to create) is only created the first time it's really used. Delaying the creation like this is called lazy loading.

In the exercise, you make a virtual proxy for a database connection. The starter has createDBConnection(). That function prints connecting..., then returns an object whose query(sql) returns "result:" + sql. You write createDBProxy(), which returns an object with a query(sql):

The starter also creates the proxy, prints proxy created, then calls query twice. The console then shows proxy created, connecting..., result:SELECT 1, then result:SELECT 2. connecting... appears only once, after proxy created. Each new proxy from createDBProxy() must pass other queries on too: query("SELECT 9") returns result:SELECT 9.

Proxy, Decorator and Adapter

All three patterns sit between the caller and other code or data. The difference is in what they do:

Some popular libraries also use the built-in Proxy. Vue 3's reactive() returns a Proxy (Vue is a framework for web pages). Its get trap records which component reads which property, and its set trap re-renders the components that read that property. Immer (a library for changing data without touching the old copy) hands you a draft that is a Proxy in produce(state, (draft) => { ... }). Changes to the draft are recorded, then Immer builds a new object.

When you don't need a proxy

⚠️ A stand-in that's too strict, or gets bypassed

TL;DR: A proxy puts a stand-in object in front of the real object. The stand-in is used the same way, and it controls access to the real object: pass on, refuse, remember answers (a cache), record, or delay creating the real object. new Proxy(RATES, handler) makes rates, a stand-in for the rates object RATES. The handler holds traps, functions that each catch one kind of operation: get for reads (refuse the unknown service overnight, record reads), set for writes (refuse the rate "$18", must return true), has for in, apply for calling a function (a cache: 3 calls, 2 requests), and so on up to 13 traps. An operation without a trap goes straight to the real object, so "express" in rates doesn't run get. Popular libraries such as Vue 3 (reactive()) and Immer use Proxy. A proxy differs from an Adapter (changes the shape) and a Decorator (adds behaviour). In the exercise, you write a virtual proxy: the database connection is only created on the first query, not when the proxy is created, and only once.

⚡ A stand-in in front of the real object

Meaning: A proxy is a stand-in object in front of the real one, used in exactly the same way. The stand-in controls access: it passes the call on to the real object, refuses it, gives an answer it saved earlier (a cache), records it, or delays creating the real object.

⚡ Traps catch operations

Write:

const rates = new Proxy(RATES, {
  get(target, prop, receiver) {
    if (!Object.hasOwn(target, prop)) throw new Error("Unknown service: " + String(prop))
    console.log("read rate " + String(prop))
    return Reflect.get(target, prop, receiver)
  },
})
Guess first: this code makes rates, a stand-in for the rates object RATES. The second object in new Proxy (the handler) only has one trap, the function get, which runs every time a property is read. in only checks whether a property exists, without reading its value. How many read rate lines appear when the code runs "express" in rates?

0 lines. in uses the has trap, not get. Since has isn't written, the operation goes straight to RATES and gives true with no log.

Meaning: new Proxy(target, handler) makes a stand-in for target. Here, get refuses a service that isn't in RATES, records the read, and then Reflect.get reads the real value. RATES isn't changed. The only change is the object callers use: rates, not RATES.

⚡ Proxy, Decorator, Adapter

Meaning: All three sit between the caller and other code. An Adapter changes the shape of the data or the way it's used. A Decorator keeps the shape and adds something, such as a fee. A Proxy keeps the shape and controls access to the real object.

What you will learn