-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathstorage.js
More file actions
64 lines (56 loc) · 1.42 KB
/
storage.js
File metadata and controls
64 lines (56 loc) · 1.42 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
'use strict';
const fs = require('node:fs');
const path = require('node:path');
const v8 = require('node:v8');
const PATH = `${__dirname}/sessions`;
const safePath = (fn) => (token, ...args) => {
const callback = args[args.length - 1];
if (typeof token !== 'string') {
callback(new Error('Invalid session token'));
return;
}
const fileName = path.join(PATH, token);
if (!fileName.startsWith(PATH)) {
callback(new Error('Invalid session token'));
return;
}
fn(fileName, ...args);
};
const readSession = safePath(fs.readFile);
const writeSession = safePath(fs.writeFile);
const deleteSession = safePath(fs.unlink);
class Storage extends Map {
get(key, callback) {
const value = super.get(key);
if (value) {
callback(null, value);
return;
}
readSession(key, (err, data) => {
if (err) {
callback(err);
return;
}
console.log(`Session loaded: ${key}`);
const session = v8.deserialize(data);
super.set(key, session);
callback(null, session);
});
}
save(key) {
const value = super.get(key);
if (value) {
const data = v8.serialize(value);
writeSession(key, data, () => {
console.log(`Session saved: ${key}`);
});
}
}
delete(key) {
console.log('Delete: ', key);
deleteSession(key, () => {
console.log(`Session deleted: ${key}`);
});
}
}
module.exports = new Storage();