6.4.2022 |

Use JavaScript Proxies for Caching

JavaScript Proxies are a way to intercept and customize operations performed on objects.

Many libraries and frameworks (e.g. Solid.js) use proxies.

A few weeks ago, I wrote about a utility function to access environment variables in Node.js which caches environment variables and throws an error when the environment variable is undefined.

You could use a JavaScript proxy for the same purpose:


const cache = {};
const cacheHandler = {
  get: (target, prop) => {
    if (target[prop]) {
      const value = Reflect.get(target, prop);
      console.log(`GET cached ${prop} with value ${JSON.stringify(value)}`);
      return value;
    } else {
      const env = process.env[prop];
      if (!env) {
        throw new ReferenceError(`Unknown environment variable: ${prop}`);
      cache[prop] = { [prop]: env, time: new Date() };
        `GET initial ${prop} with value ${JSON.stringify(cache[prop])}`
      return cache[prop];

const proxy = new Proxy(cache, cacheHandler);

const accessEnv = (key) => proxy[key];

accessEnv("DB_URL"); // GET initial DB_URL with value {"DB_URL":"mongodb://localhost:27017/db_name","time":"2022-04-06T07:22:04.303Z"}
accessEnv("DB_URL"); // GET cached DB_URL with value {"DB_URL":"mongodb://localhost:27017/db_name","time":"2022-04-06T07:22:04.303Z"}
accessEnv("DOES_NOT_EXIST"); // ReferenceError: Unknown environment variable: DOES_NOT_EXIST

The runnable code is on stackblitz.

You can also use proxies for validation via setters or to build a wrapper around HTTP calls.


Zur Übersicht

Mehr vom DevSquad...

Simon Jakubowski

Zero downtime deployment with breaking DB-Schema change - by example

Jörg Herbst

Wie SQL funktioniert