typed-storage2.2.0 • Public • Published
A wrapper for Storage implementations (local or session) that provides an easy way to store and retrieve strongly-typed, nested models.
; // typed;typedStorage.setItemmyKey, myClassInstance;// ... browser refresh ...;
- Optionally namespaced storage keys
- When so configured,
ts.getItem(aKey)can translate to
- When so configured,
- Implements the Storage interface, so the API is a superset of browser storage
- Deserializes nested models via a configurable mapper
- We use SimpleMapper for mapping, but you are free to provide your own mapper implementation during initialization.
- Understands native types:
ts.setItem("loggedIn", new Date())followed by
ts.getItem("loggedIn")will retrieve a Date object.
What it is not (anti-features)
While getItem and setItem are available in all browsers, dictionary-style references, like
are unavailable in some older browsers such as Internet Explorer (but not Edge), for example. In such browsers,
typedStorage cannot be a drop-in replacement for localStorage or sessionStorage, which
allow such references.
The specific browser feature we use is the Proxy class. See Mozilla's notes on browser support for the Proxy class, for more information.
What works in all browsers
typedStorage.setItem"keyOne", 653; // untyped; // typed;typedStorage.setItemmyKey, myClassInstance;// ... browser refresh ...; // untyped;// someValue == "653"// noTwo == myClassInstancetypedStorage.clear;typedStorage.removeItemmyKey; // redundant after clear()
typedStorage = 653;// browser refresh...;// someValue == undefined
We use SimpleMapper to recursively map deserialized objects back into their original models. Nested models should use SimpleMapper's @mappable attribute, if you want them to be recursively mapped.
You can also implement the
map() method on the
IMapper interface (below) to supply your own Or, you can wrap a 3rd-party mapper library.
Each destination property must have a default value, otherwise SimpleMapper will not be able to detect the property at run-time. The Typescript,
Custom Model Mapper
If you are going to implement a custom model mapper, you only need to implement IMapper and supply that during configuration.
npm install --save-dev typed-storage
Setup and Options
;;// Use the factory, if you want to use the Proxy interface.;
And in your classes, use it like this:
Building from source and contributing
Contributions are welcome. Please follow good code quality conventions.
npm run build to build the project. The build artifacts will be stored in the
Running unit tests
npm test or
npm run cover to execute the unit tests or tests + coverage.
While running tests, code coverage will be available at /[path/to/repo]/coverage/index.html
Run 'npm run compodoc' to generate documentation. Then run 'npm run compodoc-serve' to see auto-generated documentation and documentation coverage on port 8080.
Feel free to post issues.