Last active
September 23, 2022 12:18
-
-
Save teidesu/12e44303b0921f55f36cb6bfc5d70223 to your computer and use it in GitHub Desktop.
Proxy for localStorage that prefixes all keys.
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
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