DEV Community

loizenai
loizenai

Posted on

Ways to implement Proxy Pattern in Node.js

https://grokonez.com/node-js/ways-to-implement-proxy-pattern-in-node-js

Ways to implement Proxy Pattern in Node.js

Sometimes we may want to access indirectly to an object, via a substitute. That substitute is called Proxy. The Proxy Pattern helps us deal with a proxy object and talk to the actual object. In this tutorial, we're gonna look at 2 ways to implement Proxy Pattern in Node.js:

  • Using custom Proxy Class
  • Using Proxy API

Proxy Pattern Overview

nodejs-proxy-pattern-example-sample-structure

The image above shows that Proxy and Subject have the same methods. Proxy forwards each operation to Subject, we can improve Subject's methods with additional pre-processing or post-processing.

Proxy Pattern in Node.js using custom Class

Create Subject class

We create a Bank class with 3 methods:
deposit() increases cash.
withdraw() decreases cash.
total() returns cash.

Bank.js


class Bank {

  constructor() {
    this.cash = 0;
  }

  deposit(amount) {
    this.cash += amount;
    return this.cash;
  }

  withdraw(amount) {
    if (amount <= this.cash) {
      this.cash -= amount;
      return true;
    } else {
      return false;
    }
  }

  total() {
    return this.cash;
  }
}

module.exports = Bank;

Create custom Proxy class

The Proxy class also have 3 methods: deposit(), withdraw(), total(). Inside each method, we call Subject's methods with additional process.

Notice that we need initiate Bank object in constructor() method.

BankProxy.js

More at:

https://grokonez.com/node-js/ways-to-implement-proxy-pattern-in-node-js

Ways to implement Proxy Pattern in Node.js

Top comments (0)