UNPKG

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