-
Notifications
You must be signed in to change notification settings - Fork 87
Description
Now that we have a library for browser storage utils, we should add a class for local storage. It should have functionality for reading, editing, adding and removing items in the browser's local storage, as well as parsing the expected JSON structures with graceful error handling.
Here is a suggestion of what the signature of the class may look like:
classDiagram
class LocalStorageItem~T~ {
<<abstract>>
+key: string*
+set(value: T) void
+get() T | null
+remove() void
-isValid(content: unknown) content is T*
}
The isValid method is an abstract method that must be specified by a subclass, depending on the expected data structure of the content. It must be used by the get method to verify that the content, after being parsed from a JSON string, satisfies the T type. If the parsing fails, or if isValid returns false, get should return null and log an error message in the console.
Example of use:
type Person = {
name: string;
favouriteIceCream: string;
}
class PersonFromLocalStorage extends LocalStorageItem<Person> {
readonly key = 'person';
private isValid(content: unknown): content is Person {
// We may also use a tool like AJV here
return typeof content === 'object'
&& Object.keys(content).length === 2
&& typeof content?.name === 'string'
&& typeof content?.favouriteIceCream === 'string';
}
}
const personFromLocalStorage = new PersonFromLocalStorage();
const person: Person | null = personFromLocalStorage.get();Alternatively we could use a similar approach as for the CookieStorage class, but a drawback of that is that there is no type validation, other than ensuring the data is parsable as JSON. It may therefore lead to errors that are hard to debug, for example if we change something in the type, but users still have outdated data in their local storage. We should indeed consider changing CookieStorage to use the approach described here instead.
Metadata
Metadata
Assignees
Labels
Type
Projects
Status
Status