-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
110 lines (89 loc) · 2.78 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
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
import fs from 'fs';
const { writeFile, readFile } = fs;
export async function getJsonFile(models, path) {
try {
let json = await getData(models);
writeFile(path + Date.now() + '.txt', json, (error) => {
if (error) console.log(error);
console.log('The backup was successfully created');
});
} catch (error) {
console.log(error);
}
}
export async function saveBackupInCloud(models, Backup) {
try {
let json = await getData(models);
const backup = new Backup({
time: Date.now(),
data: json,
});
await backup.save();
console.log('The backup was successfully saved in the database');
} catch (error) {
console.log(error);
}
}
export async function restoreBackupFromCloud(models, backup, id) {
try {
backup.findById({ _id: id }).then(async (result) => {
if (!result) {
console.log('No such backup with same id');
return;
}
for (let i in models) {
await models[i].deleteMany();
}
let json = result.data;
json = JSON.parse(json);
for (let i in models) {
let data = json[models[i].collection.name];
data.forEach(async (el) => {
let element = models[i](el);
await element.save();
});
}
console.log('Database was sucessfully restored from cloud');
});
} catch (error) {
console.log(error);
}
}
export async function restoreBackupFromFile(filePath, models) {
try {
readFile(filePath, async (err, data) => {
if (err) {
console.log('No such file or directory');
return;
}
let json = data.toString();
for (let i in models) {
await models[i].deleteMany();
}
json = JSON.parse(json);
for (let i in models) {
let data = json[models[i].collection.name];
data.forEach(async (el) => {
let element = models[i](el);
await element.save();
});
}
console.log('Database was sucessfully restored from file');
});
} catch (error) {
console.log(error);
}
}
async function getData(models) {
try {
let json = {};
for (let i in models) {
await models[i].find({}).then((result) => {
json[models[i].collection.name] = result;
});
}
return JSON.stringify(json);
} catch (error) {
console.log(error);
}
}