-
Notifications
You must be signed in to change notification settings - Fork 4
/
storage.js
53 lines (46 loc) · 1.05 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
'use strict';
const fs = require('fs');
const crypto = require('crypto');
const writeCache = {};
async function storeComment(comment) {
const key = comment.itemId;
if (!writeCache[key]) {
writeCache[key] = fs.createWriteStream(`./comments/${hash(key)}.jsonl`, {
flags: 'a',
});
}
return new Promise((resolve, reject) => {
writeCache[key].write(`${JSON.stringify(comment)}\n`, 'utf8', (err) => {
if (err) {
return reject(err);
}
resolve();
});
});
}
async function readComments(itemId) {
const key = itemId;
const data = await new Promise((resolve, reject) => {
fs.readFile(`./comments/${hash(key)}.jsonl`, 'utf8', (err, data) => {
if (err) {
console.error(err);
return resolve(``);
}
resolve(data);
});
});
return data
.split('\n')
.filter((line) => line !== '')
.map((line) => JSON.parse(line));
}
module.exports = {
storeComment,
readComments,
};
function hash(str) {
return crypto
.createHash('md5')
.update(str)
.digest('hex');
}