Zwei Entwickler halten ein Meeting mit Laptop und Notizblock
Dennis, Kiya | 30.01.2024

Leveraging JavaScript Proxies for Intelligent Caching

Web > Leveraging JavaScript Proxies for Intelligent Caching

JavaScript Proxies represent a powerful mechanism for intercepting and customizing operations executed on objects.

Many libraries and frameworks, such as Solid.js, have harnessed the capabilities of proxies to enhance their functionality.

A few weeks ago, I shared an article about a utility function designed to access environment variables in Node.js. This utility efficiently caches environment variables and raises an error when an environment variable is undefined.

Interestingly, you can achieve the same objective by employing JavaScript proxies:

1require("dotenv").config();
2
3const cache = {};
4const cacheHandler = {
5  get: (target, prop) => {
6    if (target[prop]) {
7      const value = Reflect.get(target, prop);
8      console.log(`GET cached ${prop} with value ${JSON.stringify(value)}`);
9      return value;
10    } else {
11      const env = process.env[prop];
12      if (!env) {
13        throw new ReferenceError(`Unknown environment variable: ${prop}`);
14      }
15      cache[prop] = { [prop]: env, time: new Date() };
16      console.log(
17        `GET initial ${prop} with value ${JSON.stringify(cache[prop])}`
18      );
19      return cache[prop];
20    }
21  },
22};
23
24const proxy = new Proxy(cache, cacheHandler);
25
26const accessEnv = (key) => proxy[key];
27
28accessEnv("DB_URL"); // GET initial DB_URL with value {"DB_URL":"mongodb://localhost:27017/db_name","time":"2022-04-06T07:22:04.303Z"}
29console.log("-------");
30accessEnv("DB_URL"); // GET cached DB_URL with value {"DB_URL":"mongodb://localhost:27017/db_name","time":"2022-04-06T07:22:04.303Z"}
31console.log("-------");
32accessEnv("DOES_NOT_EXIST"); // ReferenceError: Unknown environment variable: DOES_NOT_EXIST

You can run the code on stackblitz to see it in action.

Additionally, JavaScript proxies find utility in various scenarios, including validation through setters or constructing wrappers for HTTP calls.

Further Reading

Content
  • What is a JavaScript Proxy?
  • How can JavaScript proxies be used for intelligent caching?
  • What other utilities do JavaScript proxies provide?
Dennis Hundertmark
Dennis (Softwareentwickler)

Als Frontend-Experte und Angular-Enthusiast gestalte ich Webanwendungen, die Technik und Design gekonnt zusammenführen. Meine Stärke liegt in der Entwicklung benutzerzentrierter Lösungen, die sowohl f... mehr anzeigen

Gitlab
Kiya

... ist unsere engagierte und leidenschaftliche Künstliche Intelligenz und Expertin für Softwareentwicklung. Mit einem unermüdlichen Interesse für technologische Innovationen bringt sie Enthusiasmus u... mehr anzeigen

Standort Hannover

newcubator GmbH
Bödekerstraße 22
30161 Hannover

Standort Dortmund

newcubator GmbH
Westenhellweg 85-89
44137 Dortmund