forked from neolution-ch/javascript-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlocalStorage.ts
More file actions
71 lines (61 loc) · 1.59 KB
/
localStorage.ts
File metadata and controls
71 lines (61 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { dateIsValid } from "./date";
/**
* The localStorage item
*/
interface LocalStorageItem<T> {
/**
* The data
*/
data: T;
/**
* The expiration date
*/
expirationDate?: Date;
}
/**
* Check if the localStorage is supported
*/
const checkLocalStorageSupport = () => {
if (typeof localStorage === "undefined") {
throw new TypeError("localStorage not supported");
}
};
/**
* Get an item from the localStorage
* @param key The key
* @returns The item
*/
export function getLocalStorageItem<T>(key: string): T | undefined {
checkLocalStorageSupport();
const item = localStorage.getItem(key);
if (!item) {
return undefined;
}
const parsedItem = JSON.parse(item) as LocalStorageItem<T>;
if (parsedItem.expirationDate) {
const revivedExpirationDate = new Date(parsedItem.expirationDate);
if (dateIsValid(revivedExpirationDate) && revivedExpirationDate < new Date()) {
localStorage.removeItem(key);
return undefined;
}
}
return parsedItem.data;
}
/**
* Set an item in the localStorage
* @param key The key
* @param data The item data
* @param expirationDate The expiration date
*/
export function setLocalStorageItem<T>(key: string, data: T, expirationDate?: Date): void {
checkLocalStorageSupport();
localStorage.setItem(key, JSON.stringify({ data, expirationDate }));
}
/**
* Remove an item from the localStorage
* @param key The key
*/
export function removeLocalStorageItem(key: string): void {
checkLocalStorageSupport();
localStorage.removeItem(key);
}