-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontenedor.js
More file actions
63 lines (53 loc) · 1.36 KB
/
contenedor.js
File metadata and controls
63 lines (53 loc) · 1.36 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
let fs = require('fs');
class Contenedor {
constructor(fileName) {
this.fileName = fileName;
this.currentId = 1;
const initialize = async (fileName) => {
if (fs.existsSync(fileName)) {
const fileContent = fs.readFileSync(fileName, 'utf-8');
this.contenedor = JSON.parse(fileContent)
this.currentId = Math.max.apply(Math, this.contenedor.map(function (o) { return o.id; })) + 1;
} else {
this.contenedor = []
}
}
initialize(fileName);
}
writeToFile = async () => {
try {
await fs.promises.writeFile(this.fileName, JSON.stringify(this.contenedor));
} catch (e) {
console.error("error escribiendo");
}
}
save = async (objeto) => {
const obj = this.contenedor.find(o => o.id === objeto.id);
if (obj) {
this.contenedor = this.contenedor.map(obj => (obj.id === objeto.id) ? objeto : obj);
} else {
objeto.id = this.currentId;
this.contenedor.push({ ...objeto, id: this.currentId });
this.currentId++;
}
await this.writeToFile();
}
getById(id) {
const result = this.contenedor.find(o => o.id === id);
return (result) ? result : null;
}
getAll() {
return this.contenedor;
}
async deleteById(id) {
this.contenedor = this.contenedor.filter(x => x.id !== id);
await this.writeToFile();
}
async deleteAll() {
this.contenedor = [];
await this.writeToFile();
}
}
module.exports = {
Contenedor,
};