Created
December 5, 2021 11:30
-
-
Save mattiasnorell/726266b3af79a527043407da512c9d65 to your computer and use it in GitHub Desktop.
Decorator that sets a Vue property to a value stored in local storage
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
import { cid, container } from 'inversify-props'; | |
import { ILocalStorageHelper } from '__helpers/storage/LocalStorageHelper'; | |
type LocalStorageOptions = { | |
storageKey: string; | |
default?: any; | |
}; | |
/** | |
* Decorator to set property values based on values stored in local storage | |
* | |
* @param {LocalStorageOptions} Options | |
* @return {*} | |
*/ | |
export function LocalStorage(options: LocalStorageOptions) { | |
const _localStorage = container.get<ILocalStorageHelper>(cid.ILocalStorageHelper); | |
const storageValue = _localStorage.read(options.storageKey); | |
let value: unknown = null; | |
if (storageValue) { | |
value = storageValue; | |
} else { | |
value = options.default; | |
} | |
return function (target: any, key: string) { | |
if (typeof value === 'function') { | |
target[key] = value.call(value); | |
} else { | |
target[key] = value; | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment