Skip to content

Instantly share code, notes, and snippets.

@mattiasnorell
Created December 5, 2021 11:30
Show Gist options
  • Save mattiasnorell/726266b3af79a527043407da512c9d65 to your computer and use it in GitHub Desktop.
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
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