storage-typed
Web Storage only accepts string value so you should write this verbose code everytime:
try {
const value = window.localStorage.getItem(key);
return value ? JSON.parse(value) : null;
} catch (e) {
}
window.localStorage.setItem(key, JSON.stringify(value));
And it does not provide any type-specific operation. (e.g. increasing number value, push to array)
const count = JSON.parse(window.localStorage.getItem(key));
window.localStorage.setItem(key, JSON.stringify(count + 1));
const arr = JSON.parse(window.localStorage.getItem(key));
window.localStorage.setItem(key, JSON.stringify([...arr, value]));
So storage-typed
resolves all things above.
const count = TypedStorageFactory.create("count", 0);
count.increase();
count.get();
const arr = TypedStorageFactory.create("array", ["foo"]);
arr.pop();
arr.push("bar");
arr.get();
API References
TypedStorageFactory
Creates TypedStorage by type of passed initial value. Note test code.
TypedStorageFactory.create<T>(key, initialValue, options);
- create:
(key, initialValue, options) => TypedStorage<T> | NumberTypedStorage | BooleanTypedStorage | ArrayTypedStorage<T[number]>
- returns instanceof
TypedStorage
by type of passed initial value - parameters
- key:
string
- required
- unique key for value
- initialValue:
T
- required
- any value which
TypedStorage
will be initialized with
- options:
TypedStorageOptions<T>
TypedStorage
Provides JSON parsing/stringifying. Note test code.
const storage = new TypedStorage<T>(key, initialValue, options);
storage.get();
storage.set(value);
TypedStorageOptions
interface TypedStorageOptions<T> {
storage?: Storage;
}
- storage:
Storage
Storage
which TypedStorage
will use
NumberTypedStorage
Extends number-specific methods based on TypedStorage
API. Note test code.
const storage = new NumberTypedStorage(key, initialValue, options);
storage.increase();
storage.decrease();
BooleanTypedStorage
Extends boolean-specific methods based on TypedStorage
API. Note test code.
const storage = new BooleanTypedStorage(key, initialValue, options);
storage.toggle();
storage.true();
storage.false();
ArrayTypedStorage
Extends number-specific methods based on TypedStorage
API. Note test code.
const storage = new ArrayTypedStorage<T>(key, initialValue, options);
storage.push(value);
storage.pop();