-
Notifications
You must be signed in to change notification settings - Fork 0
/
connector.js
107 lines (95 loc) · 2.27 KB
/
connector.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
const fs = require("fs").promises;
const { glob } = require("glob");
const hasha = require("hasha");
const srm = require("secure-rm");
let index = [];
const sha256 = (buffer) => hasha.async(buffer, { algorithm: "sha256" });
const readFiles = async (dir) => {
try {
const files = await glob(dir, {});
index = files.map((f) => ({ path: f }));
} catch(e) {
throw new Error(e)
}
}
/*
const readFiles = async (dir) =>
new Promise((resolve, reject) => {
glob(dir, {}, (er, files) => {
if (er) {
reject(er);
} else {
index = files.map((f) => ({ path: f }));
resolve(true);
}
});
});
*/
const buildIndex = async () =>
Promise.all(
index.map(async (file) => {
const buffer = await fs.readFile(file.path);
const hash = await sha256(buffer);
// eslint-disable-next-line no-param-reassign
file.sha256 = hash;
})
);
const init = async (dir) => {
try {
await readFiles(dir);
await buildIndex();
return true;
} catch (e) {
throw new Error(e);
}
};
const exists = (hash) => {
if (typeof index.find((x) => x.sha256 === hash) !== "undefined") {
return true;
}
return false;
};
const simDestroy = (hash) => {
try {
const file = index.find((x) => x.sha256 === hash);
if (typeof file !== "undefined") {
console.log(`simulated destroy of: ${file.path}`);
return true;
}
throw new Error("data not found");
} catch (e) {
throw new Error(`data could not be destroyed: ${e}`);
}
};
const wipe = async (hash) =>
new Promise((resolve, reject) => {
srm(index.find((x) => x.sha256 === hash).path)
.then(() => {
resolve(true);
})
.catch((err) => {
reject(err);
});
});
const destroy = async (hash) => {
try {
const file = index.find((x) => x.sha256 === hash);
if (typeof file !== "undefined") {
await fs.unlink(file.path);
return true;
}
throw new Error("data not found");
} catch (e) {
throw new Error(`data could not be destroyed: ${e}`);
}
};
const sha256FileHash = {
exists: (hash) => exists(hash),
wipe: async (hash) => wipe(hash),
destroy: async (hash) => destroy(hash),
simDestroy: (hash) => simDestroy(hash),
};
module.exports = {
init,
sha256FileHash,
};