The first in a series exploring different JS features in 300 words or less
Hey you! That’s right, it’s another blog post about Javascript (boring, am I right?)! Today though, we’re going to explore one of the most interesting features of the JS language for metaprogramming and building abstractions: Proxies!
To construct a contrived example, let’s say you’re building a website that fetches some data from the backend, and you’ve got a simple NodeJS server somewhat like this (the details are completely unimportant, as long as you get the gist of what’s going on):
app.get("/friends", (req, res) => {
return res.json([
{
name: "Mr Bean",
username: "mr-bean"
},
{
name: "Darth Vader",
username: "officialV"
}
])
})
Now to the interesting stuff—how would you fetch that from the frontend? The normal way (and quite frankly the sane way), would be to do something like:
const friends = await fetch("/friends").then(r => r.json())
But hey, that’s no fun! What if instead you could simply write const friends = await server.friends()
? That’s where Proxies come in. They’ve got a bunch of interesting properties that you can read all about on [MDN], but for our purposes what they do really well is let you intercept property access (i.e. the getting of the property friends
on the server
object). It looks like this:
const server = new Proxy({}, {
get(_, property) {
return async () => {
return fetch(`/${property}`).then(r => r.json())
}
}
})
This will make every property access on the server
object return an async function that fetches the path /${propery}
. And that’s it! Now you can write await server.whatever()
to your hearts content, knowing that it’ll make the right network request.
Top comments (0)