Repository navigation
Expand file tree
/
Copy pathbase-storage.js
More file actions
108 lines (94 loc) · 2.5 KB
/
Copy pathbase-storage.js
File metadata and controls
108 lines (94 loc) · 2.5 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
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
import { createStore, hasOwn, parseValue, stringifyValue } from './helpers.js';
const TTL_SUFFIX = '.___exp';
/**
* Base class for shared storage logic: cache, TTL handling, common methods.
* Reduces duplication across drivers. Drivers extend and implement storage-specific ops.
* @locus Client
*/
class BaseStorage {
constructor(clientStorage) {
if (clientStorage && clientStorage.data) {
this.data = clientStorage.data;
this.ttlData = clientStorage.ttlData;
} else {
this.data = createStore();
this.ttlData = createStore();
}
this.TTL_SUFFIX = TTL_SUFFIX;
}
/**
* Check if TTL expired for key. Auto cleanup on access.
*/
_checkTTL(key) {
if (!hasOwn(this.ttlData, key)) return false;
const expireAt = Number(this.ttlData[key]);
if (!Number.isFinite(expireAt) || expireAt <= Date.now()) {
this.remove(key);
return true;
}
return false;
}
get(key) {
if (typeof key !== 'string') return void 0;
if (!hasOwn(this.data, key)) return void 0;
if (this._checkTTL(key)) return void 0;
return this.data[key];
}
has(key) {
if (typeof key !== 'string') return false;
if (!hasOwn(this.data, key)) return false;
if (this._checkTTL(key)) return false;
return true;
}
keys() {
return Object.keys(this.data).filter((key) => !this._checkTTL(key));
}
empty() {
return this.remove();
}
set(key, value, ttl) {
if (typeof key !== 'string') return false;
this.data[key] = value;
if (typeof ttl === 'number' && ttl > 0) {
const expireAt = Date.now() + (ttl * 1000);
this.ttlData[key] = expireAt;
} else {
delete this.ttlData[key];
}
return true;
}
remove(key) {
if (key !== void 0 && typeof key !== 'string') return false;
if (typeof key === 'string') {
if (hasOwn(this.data, key)) {
delete this.data[key];
delete this.ttlData[key];
return true;
}
return false;
}
// empty all (key is undefined)
const keys = this.keys();
if (keys.length === 0) return false;
for (let i = 0; i < keys.length; i++) {
this.remove(keys[i]);
}
return true;
}
escape(val) {
return encodeURIComponent(stringifyValue(val));
}
unescape(val) {
let decoded = val;
try {
decoded = decodeURIComponent(val);
} catch (_) {
// malformed URI sequence — keep raw value
}
return parseValue(decoded);
}
static isSupported() {
return true;
}
}
export default BaseStorage;