UNPKG

3.08 kBJavaScriptView Raw
1/**
2 * @hidden
3 */
4var LocalStorageStrategy = (function () {
5 function LocalStorageStrategy() {
6 }
7 LocalStorageStrategy.prototype.get = function (key) {
8 return localStorage.getItem(key);
9 };
10 LocalStorageStrategy.prototype.set = function (key, value) {
11 return localStorage.setItem(key, value);
12 };
13 LocalStorageStrategy.prototype.delete = function (key) {
14 return localStorage.removeItem(key);
15 };
16 return LocalStorageStrategy;
17}());
18export { LocalStorageStrategy };
19/**
20 * @hidden
21 */
22var SessionStorageStrategy = (function () {
23 function SessionStorageStrategy() {
24 }
25 SessionStorageStrategy.prototype.get = function (key) {
26 return sessionStorage.getItem(key);
27 };
28 SessionStorageStrategy.prototype.set = function (key, value) {
29 return sessionStorage.setItem(key, value);
30 };
31 SessionStorageStrategy.prototype.delete = function (key) {
32 return sessionStorage.removeItem(key);
33 };
34 return SessionStorageStrategy;
35}());
36export { SessionStorageStrategy };
37/**
38 * A generic local/session storage abstraction.
39 */
40var Storage = (function () {
41 function Storage(deps, options) {
42 if (options === void 0) { options = { 'prefix': 'ionic', 'cache': true }; }
43 this.options = options;
44 this.strategy = deps.strategy;
45 this.storageCache = {};
46 }
47 /**
48 * Set a value in the storage by the given key.
49 *
50 * @param key - The storage key to set.
51 * @param value - The value to set. (Must be JSON-serializable).
52 */
53 Storage.prototype.set = function (key, value) {
54 key = this.standardizeKey(key);
55 var json = JSON.stringify(value);
56 this.strategy.set(key, json);
57 if (this.options.cache) {
58 this.storageCache[key] = value;
59 }
60 };
61 /**
62 * Delete a value from the storage by the given key.
63 *
64 * @param key - The storage key to delete.
65 */
66 Storage.prototype.delete = function (key) {
67 key = this.standardizeKey(key);
68 this.strategy.delete(key);
69 if (this.options.cache) {
70 delete this.storageCache[key];
71 }
72 };
73 /**
74 * Get a value from the storage by the given key.
75 *
76 * @param key - The storage key to get.
77 */
78 Storage.prototype.get = function (key) {
79 key = this.standardizeKey(key);
80 if (this.options.cache) {
81 var cached = this.storageCache[key];
82 if (cached) {
83 return cached;
84 }
85 }
86 var json = this.strategy.get(key);
87 if (!json) {
88 return null;
89 }
90 try {
91 var value = JSON.parse(json);
92 if (this.options.cache) {
93 this.storageCache[key] = value;
94 }
95 return value;
96 }
97 catch (err) {
98 return null;
99 }
100 };
101 /**
102 * @private
103 */
104 Storage.prototype.standardizeKey = function (key) {
105 return this.options.prefix + "_" + key;
106 };
107 return Storage;
108}());
109export { Storage };