Pattern Proxy
Tags: webdev, javascript, programming, tutorial
Published: 2023-04-07 00:27:56


![Pattern Proxy](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1rnqmj2xcf1ghij4newm.jpg)

The origin of the proxy design pattern dates back to the 1990s, when the book “Design Patterns: Elements of Reusable Object-Oriented Software” was published by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides.

Pattern Proxy is a software design pattern for controlling access to an object or resource. It works by creating an intermediate object, called a proxy, which acts as a stand-in for the real object.

The Proxy pattern is useful in situations where you want to control access to an object or resource in a more granular way, allowing or denying access as needed. Some cases where the Proxy pattern can be useful include:

- Reduced resource usage: If an object is expensive in terms of resources such as memory or processing, using a proxy can help reduce the number of times the object is created or accessed, improving system efficiency.
- Access control: the proxy can be used to control access to sensitive or critical objects, allowing only authorized users to have access to them. This helps ensure system security.
- Remote object management: Remote proxy is used to access remote objects in a distributed system, allowing clients to access remote objects as if they were accessing local objects.
- Creation on demand: Virtual proxy is used to create objects on demand, avoiding unnecessary creation of expensive objects. This helps to improve system efficiency. In summary, the Proxy pattern is useful whenever there is a need to control access to an object or resource in a more granular way, ensuring the efficiency and security of the system.

There are several types of proxy such as remote proxy, virtual proxy and shield proxy. Remote proxy is used to access remote objects in a distributed system while virtual proxy is used to create objects on demand, avoiding unnecessary creation of expensive objects. The protection proxy is used to control access to sensitive or critical objects.

The proxy pattern is one of the most popular and widely used design patterns in software programming. It helps improve system efficiency and security by ensuring controlled and secure access to important objects and resources.

Below is an example of implementing the Proxy pattern in Node.js with REST API consumption.

```js
const axios = require('axios');

class CacheProxyApi {
  constructor() {
    this.url = 'https://api.example.com.br'
    this.cache = {};
  }
  async get(path) {
    if (this.cache[path]) {
      console.log(`Retrieved data from cache for path: ${path}`);
      return Promise.resolve(this.cache[path]);
    }
    console.log(`Fetching data from API for endpoint: ${path}`);
    const response = await axios.get(`${this.url}${path}`);
    this.cache[path] = response.data;
    return Promise.resolve(response.data);
  }
}
module.exports = CacheProxyApi;
```

In this example, the CacheProxyApi class acts as a proxy for the external API, caching the results of calls to avoid unnecessary API calls. The get method is responsible for making the API call and returning the data. If the result is already cached, it will be returned immediately.

To use the proxy, just create an instance of the CacheProxyApi class and call the get method with the desired endpoint:

```js
const CacheProxyApi = require('./CacheProxyApi');
const cacheProxyApi = new CacheProxyApi();
cacheProxyApi.get('users')
  .then(data => console.log(data))
  .catch(error => console.error(error));
```

In this example, the proxy is used to fetch user data from the external API. If the data is already cached, the proxy returns it immediately without making an API call. If the data is not cached, the proxy fetches the data from the API and caches it for future use.

Simple, right?

The use of the Proxy pattern brings several advantages, some of them are:

- Access Control: The Proxy pattern allows access to sensitive objects or resources to be controlled, allowing only authorized users to access these objects. This helps ensure system security.
- Reducing resource usage: Proxy can be used to reduce resource usage, avoiding unnecessary creation of expensive objects and reducing the number of accesses to remote objects, for example. This helps to improve system efficiency.
- On-Demand Creation: Virtual Proxy is used to create objects on demand, avoiding unnecessary creation of expensive objects. This helps to improve system efficiency and reduce resource usage.
- Improves performance: Using Proxy can help improve system performance by reducing network load and minimizing data traffic between the client and the server.
- Code simplification: The Proxy pattern can help simplify code, allowing developers to focus on specific business logic rather than worrying about access control implementation details and resource management.


## Conclusion

In short, the Proxy pattern is a powerful technique for improving the efficiency, security, and performance of systems, allowing for more granular access control and more efficient resource management.