/
offlineStorage.js
102 lines (87 loc) · 2.5 KB
/
offlineStorage.js
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import Adapt from 'core/js/adapt';
// Basic API for setting and getting name+value pairs
// Allows registration of a single handler.
class OfflineStorage extends Backbone.Controller {
/**
* set .ready to false if an offlineStorage handler is being attached - we'll need to wait until the handler lets us know
* it's ready before we can safely use offlineStorage
*/
initialize(handler) {
/**
* set to true initially so that if there are no offlineStorage handlers (i.e. if contrib-spoor is not installed)
* this can still be accessed OK
*/
this.ready = true;
this._handler = undefined;
if (!handler) {
return;
}
this.ready = false;
this._handler = handler;
}
/**
* Flag to indicate if an offlineStorage handler has been defined.
* @returns {boolean} true if an offlineStorage handler has been defined, false otherwise
*/
hasHandler() {
return this._handler !== undefined;
}
/**
* Causes state to be serialized and saved.
*/
save() {
Adapt.trigger('tracking:save');
return this._handler?.save?.(...arguments);
}
/**
* Serializes nested arrays, booleans and numbers into an encoded string.
* @param {Array|boolean|number} value
* @returns {string}
*/
serialize(value) {
if (this._handler?.serialize) {
return this._handler.serialize(...arguments);
}
return JSON.stringify(value);
}
/**
* Deserializes encoded strings back into nested arrays, booleans and numbers.
* @param {string} value
* @returns {Array|boolean|number}
*/
deserialize(value) {
if (this._handler?.deserialize) {
return this._handler.deserialize(...arguments);
}
return JSON.parse(value);
}
set(name, value) {
if (this._handler?.set) {
return this._handler.set(...arguments);
}
// if no handler has been defined, just store the data locally
this[name] = value;
}
get(name) {
if (this._handler?.get) {
return this._handler.get(...arguments);
}
// if no handler has been defined, check local data store
return this[name];
}
clear() {
if (this._handler?.clear) {
return this._handler.clear(...arguments);
}
return false;
}
/**
* Some forms of offlineStorage could take time to initialise, this allows us to let plugins know when it's ready to be used
*/
setReadyStatus() {
this.ready = true;
Adapt.trigger('offlineStorage:ready');
}
}
const offlineStorage = new OfflineStorage();
export default offlineStorage;