Pattern Proxy
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:
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.
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:
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:
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.