forked from xdrip-js/Lookout
-
Notifications
You must be signed in to change notification settings - Fork 0
/
storage.js
123 lines (91 loc) · 2.39 KB
/
storage.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
let storage = null;
const Debug = require('debug');
const moment = require('moment');
const log = Debug('storage:log'); /* eslint-disable-line no-unused-vars */
const error = Debug('storage:error'); /* eslint-disable-line no-unused-vars */
const debug = Debug('storage:debug'); /* eslint-disable-line no-unused-vars */
const storageLock = require('./storageLock');
const getItem = async (name) => {
let returnVal = null;
if (!storage) {
throw Error('Storage not initialized');
}
try {
returnVal = await storage.getItem(name);
} catch (e) {
error(`Unable to read item ${name}:`, e);
returnVal = null;
}
return returnVal;
};
const getEvent = async (name) => {
if (!storage) {
throw Error('Storage not initialized');
}
try {
let item = await getItem(name);
if (item) {
if (typeof item === 'number') {
item = {
date: moment(item),
notes: '',
};
} else {
item.date = moment(item.date);
}
}
return item;
} catch (e) {
error(`Unable to read item ${name}:`, e);
return null;
}
};
const getArray = async (name) => {
let arrayVal = await getItem(name);
if (!arrayVal) {
arrayVal = [];
}
return arrayVal;
};
const setItem = async (name, value) => {
if (!storage) {
throw Error('Storage not initialized');
}
return storage.setItem(name, value);
};
const setEvent = async (name, value) => {
if (!storage) {
throw Error('Storage not initialized');
}
const saveValue = {
date: value.date.valueOf(),
notes: value.notes,
};
return storage.setItem(name, saveValue);
};
const setItemSync = (name, value) => {
if (!storage) {
throw Error('Storage not initialized');
}
return storage.setItemSync(name, value);
};
const delItem = async (name) => {
if (storage) {
return storage.del(name);
}
throw Error('Storage not initialized');
};
module.exports = {
init: (newStorage) => {
storage = newStorage;
},
getItem: async name => getItem(name),
getEvent: async name => getEvent(name),
getArray: async name => getArray(name),
setItem: async (name, value) => setItem(name, value),
setEvent: async (name, value) => setEvent(name, value),
setItemSync: (name, value) => setItemSync(name, value),
delItem: async name => delItem(name),
lock: async () => storageLock.lockStorage(),
unlock: () => storageLock.unlockStorage(),
};