Skip to content

Instantly share code, notes, and snippets.

@teidesu
Last active September 23, 2022 12:18
Show Gist options
  • Save teidesu/12e44303b0921f55f36cb6bfc5d70223 to your computer and use it in GitHub Desktop.
Save teidesu/12e44303b0921f55f36cb6bfc5d70223 to your computer and use it in GitHub Desktop.
Proxy for localStorage that prefixes all keys.
const prefix = 'prefix_'
const rawLS = window.localStorage
const wrappedLS = new Proxy(rawLS, {
get(target, prop, receiver) {
if (typeof target[prop] === 'function') {
return function(key, value) {
return target[prop](prefix + key, value)
}
}
return target[prefix + prop]
},
set(target, prop, value) {
target[prefix + prop] = value
return true
},
deleteProperty(target, prop) {
delete target[prefix + prop]
return true
},
has(target, prop) {
return (prefix + prop) in target
},
ownKeys(target) {
return Object.keys(target).filter(it => it.startsWith(prefix)).map(it => it.substring(prefix.length))
},
enumerate(target) {
return Object.keys(target).filter(it => it.startsWith(prefix)).map(it => it.substring(prefix.length))
},
getOwnPropertyDescriptor(target, prop) {
const val = target[prefix + prop]
return val ? {
value: val,
writable: true,
enumerable: true,
configurable: true
} : undefined
}
})
Object.defineProperty(window, 'localStorage', { value: wrappedLS })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment