Fun with JavaScript Proxy
JavaScript Proxies are pure sugar 🍯 when you want to build some generic logic in your applications to make your life easier. Here is one example:
Client Server Communication
We are using a JavaScript Proxy instance on the client side as a wrapper around an HTTP (network) service. The final usage will then look like:
await server.saveUsername(username); // 🚀
The Proxy instance server
is taking the called property key saveUsername
and makes an HTTP request to the real server with the given data. The proxy implementation looks like:
export const server = new Proxy({}, {
get(_, key) {
return async (data) => {
return await makeHttpPostRequest(`/${key}`, data);
};
}
}); // 😮
The HTTP request itself can be sent via the native fetch
method or any library like axios
.
On the server side we can do some nice implemenation too, to map this structure. In your NodeJS (Express) server app just method all API methods, so that they can be called by the client via the proxy. That looks like:
// Load all API methods
const api = require("./api.js");
// Construct the express server app
const app = express();
// Listen for incoming HTTP POST requests
Object.keys(api).forEach(methodName => {
app.post(`/${methodName}`, api[methodName]);
});
The logic shown above maps all methods from api.js
so that we are listening for incoming POST HTTP requests with the method name as path.
For our example the server side implementation would then look like (api.js):
module.exports = {
saveUsername(req, res) {
// TODO: save username
res.send({
success: "true"
});
}
};
So, whatever method you put into your api.js
file, it’s immediately available from the client side. That way you save time and the code looks nice and clean.
Get The Code
Here is the code on GitHub:
👉 https://github.com/dobschal/javascript-proxy-fun
Here is an explanation video:
👉 https://www.youtube.com/watch?v=SCHHFcGWRLQ
I am open for feedback, so leave a comment.
More about me: https://dobschal.eu
Thanks! ❤️