-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
executable file
·118 lines (100 loc) · 2.67 KB
/
index.js
File metadata and controls
executable file
·118 lines (100 loc) · 2.67 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
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
const path = require('path');
const fs = require('fs');
const Ajv = require('ajv');
const pluralize = require('pluralize');
const transliterate = require('@javascriptru/transliterate');
const uuid = require('uuid/v4');
module.exports = class Db {
constructor({dataPath, schemasPath}) {
this.filePath = dataPath;
let schemas = require(schemasPath);
this.ajv = new Ajv({
schemas,
allErrors: true,
// verbose: true
});
}
getAll() {
return this.data;
}
get(key) {
return this.data[key];
}
getById(collection, id) {
collection = this.data[collection];
if (Array.isArray(collection)) {
return collection.find(item => item.id == id);
}
}
set(key, value) {
this.data[key] = value;
}
update(key, value) {
Object.assign(this.data[key], value);
}
load() {
if (!fs.existsSync(this.filePath)) {
this.data = {};
return;
}
this.data = this.deserialize(fs.readFileSync(this.filePath, 'utf-8'));
}
save() {
if (!process.env.DB_SAVE_DISABLED) {
fs.writeFileSync(this.filePath, this.serialize(this.data));
}
}
deserialize(json) {
return JSON.parse(json, (key, value) => {
if (key === 'createdAt' || key === 'modifiedAt') {
return new Date(value);
} else {
return value;
}
});
}
serialize(json) {
return JSON.stringify(json, null, 2);
}
// product/db/...
getValidate(name) {
return this.ajv.getSchema(name);
}
validateAll() {
// fixme
let validate = this.ajv.getSchema('db');
if (!validate({db: this.data})) {
console.error(validate.errors);
throw new Error("Validation error");
}
}
// autogenerate id
createId(collection, resource) {
if (resource.title) {
return transliterate(resource.title);
} else {
return uuid();
}
}
// returns a function that gets required field from value, including subfields
// getter = createGetter('category')
// getter(product) // gets product.category
// getter = createGetter('category.name')
// getter(product) // gets product.category.name (finds category in db)
createGetter(field) {
// category.name -> ['category','name']
const parts = field.split('.');
return value => {
for (let i = 0; i < parts.length; i++) {
value = value[parts[i]]; // from product -> get product.category (id)
if (value === undefined) return undefined;
if (i < parts.length - 1) {
// we have category id, let's get category instead
let collection = this.get(pluralize(parts[i]));
value = collection.find(v => v.id == value);
}
}
return value;
};
}
}