-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
110 lines (95 loc) · 2.52 KB
/
index.ts
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 {
LocalFileSystemDuplexConnector,
MongoDBDuplexConnector,
MongoTransferer,
} from "mongodb-snapshot";
import { scheduleJob } from "node-schedule";
import "dotenv/config";
import path from "path";
const monthNames = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
];
function nameGenerator() {
const now = new Date();
const name = `${now.getDate()}-${
monthNames[now.getMonth()]
}-${now.getFullYear()}`;
if (process.env["USE_TIMESTAMP"]) {
// Add hour, minute and second to the name
return `${name}-${now.getHours()}-${now.getMinutes()}-${now.getSeconds()}.tar`;
}
return `${name}.tar`;
}
function createBackupFolder() {
// Create backup folder if not exists
const fs = require("fs");
const directory = process.env["BACKUP_TO_LOCAL_PATH"];
if (!fs.existsSync(directory)) {
fs.mkdirSync(directory);
}
}
async function backupDB() {
createBackupFolder();
const mongo_connector = new MongoDBDuplexConnector({
connection: {
uri: process.env["DB_URL"],
dbname: process.env["DB_NAME"],
},
});
const localfile_connector = new LocalFileSystemDuplexConnector({
connection: {
path: path.join(process.env["BACKUP_TO_LOCAL_PATH"], nameGenerator()),
},
});
const transferer = new MongoTransferer({
source: mongo_connector,
targets: [localfile_connector],
});
for await (const { total, write } of transferer) {
console.log(`remaining bytes to write: ${total - write}`);
}
}
function deleteOldBackups() {
createBackupFolder();
const fs = require("fs");
const directory = process.env["BACKUP_TO_LOCAL_PATH"];
fs.readdir(directory, (err: any, files: any) => {
if (err) throw err;
if (files.length > process.env["KEEP_BACKUP_FILES"]) {
//Delete the oldest files
files
.sort((a: any, b: any) => {
return (
fs.statSync(path.join(directory, a)).mtime.getTime() -
fs.statSync(path.join(directory, b)).mtime.getTime()
);
})
.slice(0, files.length - (process.env["KEEP_BACKUP_FILES"] as any))
.forEach((file: any) => {
console.log(`Deleting ${file}`);
fs.unlinkSync(path.join(directory, file));
console.log(`Deleted ${file}`);
});
}
});
}
function startSchedule() {
scheduleJob(process.env["SCHEDULE_TIME"], async () => {
console.log("Backup started");
await backupDB();
deleteOldBackups();
console.log("Backup completed");
});
}
startSchedule();