Reputation: 85
I have a remote key/value store with a simple .get()/.put()
interface. I want to call someProxyObject.route1.route2.route3
and have this resolve to a call to storageObject.retrieve(["route1", "route2", "route3"])
. The goal is to treat the remote storage like a local object. I am currently using the following code to collect the route.
var validator = {
route: [],
get(target, key) {
this.route.push(key)
console.log(String(this.route), "get");
return new Proxy(target, validator)
},
set (target, key, value) {
this.route.push(key)
console.log(String(this.route), "set");
return false
},
deleteProperty (target, key) {
this.route.push(key)
console.log(String(this.route), "delete");
return target;
}
}
let storage = new Proxy({}, validator);
storage.p1.p2.p3.p4 = 1
validator.route = []
storage.p1.p2.p3.p4
As you can see from running the above code, when I set or delete a value, there is a recursion of get
calls and then a resolving delete/set
call. The issue is having no resolving call for a simple get
chain. Can you devise a method to act upon the final .routeX
to allow for a final resolution? EDIT: My goal is to avoid placing a final call like .resolve
at the end of the chain
Upvotes: 0
Views: 557
Reputation: 94101
I know this doesn't quite answer your question, but you could just add an extra .route
to resolve the chain. You don't even need a setter:
function createStorage() {
const route = [];
function createProxy() {
return new Proxy({}, {
get(_0, key) {
if (key === 'route') {
return route;
}
route.push(key);
return createProxy();
}
});
}
return createProxy();
}
const storage = createStorage();
console.log(storage.p1.p2.p3.route); //=> ['p1', 'p2', 'p3']
In the same way, you could also have a clear
key that will reset the route array so you don't access the state directly.
Upvotes: 1