Last active
August 20, 2021 11:12
-
-
Save traffisco/32de8ee2850c437bb367cbc8485fb870 to your computer and use it in GitHub Desktop.
Make localStorage as simple read/write object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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._setItem = Storage.prototype.setItem; | |
Storage.prototype.setItem = function(target, prop){ | |
try { | |
this.proxy[target] = JSON.parse(prop); | |
} catch { | |
this.proxy[target] = prop; | |
} | |
this._setItem(target,prop); | |
} | |
Storage.prototype._removeItem = Storage.prototype.removeItem; | |
Storage.prototype.removeItem = function(target){ | |
delete this.proxy[target]; | |
this._removeItem(target); | |
} | |
Storage.prototype.update = function () { | |
obj = this.proxy; | |
Object.keys(obj).forEach(key => { | |
this._setItem(key, JSON.stringify(obj[key])); | |
}); | |
Object.keys(this).forEach(key => { | |
if (!(key in obj)) { | |
this._removeItem(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] != null && !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) { | |
if (target instanceof Array) { | |
target.splice(prop, 1); | |
} else { | |
delete target[prop]; | |
} | |
localStorage.update(); | |
} | |
return true; | |
} | |
}); | |
const storage = localStorage.dynamic; | |
storage.new = {}; | |
storage.new.one = 1; | |
storage.new.one; // 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment