forked from codebymitch/TitanBot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemoryStorage.js
More file actions
96 lines (79 loc) · 2.51 KB
/
Copy pathmemoryStorage.js
File metadata and controls
96 lines (79 loc) · 2.51 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
// memoryStorage.js
import { logger } from './logger.js';
class MemoryStorage {
constructor() {
this.data = new Map();
this.expirationTimes = new Map();
}
async get(key, defaultValue = null) {
const value = this.data.get(key);
if (this.expirationTimes.has(key)) {
const expirationTime = this.expirationTimes.get(key);
if (Date.now() > expirationTime) {
this.data.delete(key);
this.expirationTimes.delete(key);
return defaultValue;
}
}
return value !== undefined ? value : defaultValue;
}
async set(key, value, ttl = null) {
this.data.set(key, value);
if (ttl && ttl > 0) {
this.expirationTimes.set(key, Date.now() + (ttl * 1000));
}
return true;
}
async delete(key) {
this.data.delete(key);
this.expirationTimes.delete(key);
return true;
}
async list(prefix) {
const keys = [];
for (const key of this.data.keys()) {
if (key.startsWith(prefix)) {
if (this.expirationTimes.has(key)) {
const expirationTime = this.expirationTimes.get(key);
if (Date.now() > expirationTime) {
this.data.delete(key);
this.expirationTimes.delete(key);
continue;
}
}
keys.push(key);
}
}
return keys;
}
async exists(key) {
const value = this.data.get(key);
if (this.expirationTimes.has(key)) {
const expirationTime = this.expirationTimes.get(key);
if (Date.now() > expirationTime) {
this.data.delete(key);
this.expirationTimes.delete(key);
return false;
}
}
return value !== undefined;
}
async increment(key, amount = 1) {
const current = await this.get(key, 0);
const newValue = current + amount;
await this.set(key, newValue);
return newValue;
}
async decrement(key, amount = 1) {
const current = await this.get(key, 0);
const newValue = current - amount;
await this.set(key, newValue);
return newValue;
}
async clear() {
this.data.clear();
this.expirationTimes.clear();
return true;
}
}
export { MemoryStorage };