I want to proxy localStorage setters and getters to parse objects and save them to storage on assignment like I use a regular object.
Pretty straight forward when saving single KV items but complicated(for me) when trying to update a nested object in the storage.
The problem I have is how to get the correct position in the object using the target parameter. To overcome this problem, I prototyped the proxy object back to localStorage and parse it every time the proxy calls set.
It works like expected but doesn't look like the proper way to do it.
Any advice be appreciated.
Storage.prototype.proxy = {}
Storage.prototype.getAll = function () {
data = {};
Object.keys(this).forEach(key => {
try {
data[key] = JSON.parse(this[key])
} catch {
data[key] = this[key]
}
});
this.proxy = data;
return this.proxy;
}
Storage.prototype.update = function () {
this.clear();
obj = this.proxy;
Object.keys(obj).forEach(key => {
this.setItem(key, JSON.stringify(obj[key]));
});
}
Storage.prototype.dynamic = new Proxy(localStorage.getAll(), handler = {
get(target, prop) {
if (prop == 'isProxy') return true;
if (typeof target[prop] == 'undefined') return;
if (!target[prop].isProxy && typeof target[prop] === 'object') {
target[prop] = new Proxy(target[prop], handler);
}
return Reflect.get(...arguments);
},
set() {
Reflect.set(...arguments);
localStorage.update();
return true;
},
deleteProperty(target, prop) {
if (prop in target) {
delete target[prop];
localStorage.update();
}
}
});
const storage = localStorage.dynamic;
storage.new = {}; //create new key in storage that hold an object
storage.new.one = 1; //create new object in and assign 1 to it
console.log(storage.new.one); // prints 1