-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmy-key-value-store.js
122 lines (97 loc) · 2.96 KB
/
my-key-value-store.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
const fs = require('fs');
const path = require('path');
const mkdirpSync = require('mkdirp').sync;
function Store(filePath, opts) {
opts = opts || getDefaultOpts();
this.opts = opts;
this.opts.timespanInMs = opts.timespanInMs || getDefaultOpts().timespanInMs;
this.filePath = filePath;
this.data = {};
this.saveTimeout = null;
this.savingInProgress = false;
const self = this;
this.set = function(key, value) {
if (typeof key === 'object' || key.indexOf('Object') >= 0) {
throw new Error(`Can't use object as a key ${key} ${value}`);
}
key = key.toString();
this.data[key] = value;
if (!this.saveTimeout) {
this.saveTimeout = setTimeout(this._writeFile.bind(this), this.opts.timespanInMs);
}
return value;
};
this.get = function(key) {
key = key.toString();
const value = this.data[key];
if (!value) {
return null;
}
return JSON.parse(JSON.stringify(value));
};
this.getAll = function () {
return Object.values(this.data);
};
this.count = function () {
return this.getAll().length;
};
// TODO: (maybe) add orderFn
this.getByFilter = function(filterFn, limit) {
const selected = Object.keys(this.data);
const items = [];
limit = limit || selected.length;
for (
let i = 0;
items.length < limit && i < selected.length;
i++
) {
const key = selected[i];
const value = this.data[key];
if (filterFn(value, key)) {
items.push(value);
}
}
return JSON.parse(JSON.stringify(items));
};
this._writeFile = () => {
if (!this.savingInProgress) {
const jsonData = JSON.stringify(this.data, null, 2);
fs.writeFile(this.filePath, jsonData, { mode: 0o0600 }, (err) => {
if (err) {
console.error(err);
}
this.saveTimeout = null;
this.savingInProgress = false;
});
this.savingInProgress = true;
}
};
this.load = () => {
try {
return (this.data = JSON.parse(fs.readFileSync(this.filePath)));
} catch (err) {
if (err.code === 'EACCES') {
err.message += '\ndata-store does not have permission to load this file\n';
throw err;
}
if (err.code === 'ENOENT' || err.name === 'SyntaxError') {
this.data = {};
return {};
}
if (err) {
console.error(err);
}
}
};
function prepare() {
mkdirpSync(path.dirname(self.filePath));
self.load();
}
function getDefaultOpts() {
return {
timespanInMs: 5000
};
}
prepare();
}
module.exports = Store;