-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
54 lines (51 loc) · 1.83 KB
/
index.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
//==============================================================================
// ■ Database (fsdb/index.js)
//------------------------------------------------------------------------------
// Database access logic.
//==============================================================================
const $file = require("./file");
const $crud = require("./crud/");
//------------------------------------------------------------------------------
// ● Setup-Collection
//------------------------------------------------------------------------------
function $collection(collectionName, data, $save) {
let collection = data[collectionName];
if (!collection) {
collection = data[collectionName] = [];
}
collection.name = collectionName;
collection.db = data;
collection.save = async () => await $save(data);
return collection;
}
//------------------------------------------------------------------------------
// ● Database-API
//------------------------------------------------------------------------------
async function fsdb(fileName, dirName) {
const { $filePath, $load, $save } = $file(fileName, dirName);
console.log("[fsdb]", $filePath);
let data = {};
try {
data = await $load();
console.log("[fsdb] File found. Data loaded.");
} catch (err) {
if (err.code === "ENOENT") {
console.log("[fsdb] No such a file. New data created.");
}
}
const db = collectionName => {
const collection = $collection(collectionName, data, $save);
return $crud(collection);
};
db.filePath = $filePath;
db.data = data;
db.drop = async () => {
data = {};
await $save(data);
};
return db;
}
//------------------------------------------------------------------------------
// ► Exports
//------------------------------------------------------------------------------
module.exports = fsdb;