-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
74 lines (62 loc) · 1.95 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
const path = require('path');
const fs = require('fs');
const { exec } = require('child_process');
const aws = require('aws-sdk');
module.exports = function({ bucketName, accessKey, accessSecret }) {
const s3Bucket = new aws.S3({
accessKeyId: accessKey,
secretAccessKey: accessSecret,
Bucket: bucketName,
});
function dumpDatabase({ uri, backupName, gzip }, callback = (err, backupPath) => {}) {
const dumpPath = path.resolve(__dirname, backupName)
const command = `mongodump --uri="${uri} ${gzip ? ' --gzip' : ''}" --archive="${dumpPath}"`;
exec(command, (err, stdout, stderr) => {
// We cannot trust stderr cause mongo spits warnings/logs on this channel
// so we check if the dump was created
if (err) {
return callback(err);
}
if (!fs.existsSync(dumpPath)) {
return callback(new Error('Something went wrong'));
}
return callback(null, dumpPath);
})
}
function uploadToS3(file, fileName, callback = (err, data) => {}) {
s3Bucket.upload({
Bucket: bucketName,
Key: fileName,
Body: file
}, (err, data) => {
if (err) {
return callback(err);
}
return callback(null, data);
})
}
return {
backupDatabase({ uri, backupName, gzip }, callback = () => {}) {
return new Promise((resolve, reject) => {
if (!uri || !backupName) {
throw new Error('uri and backupName are required parameters');
}
dumpDatabase({uri, backupName, gzip}, (err, backupPath) => {
if (err) {
callback(err);
return reject(err);
}
uploadToS3(fs.createReadStream(backupPath), backupName, (err, data) => {
if (err) {
callback(err);
return reject(err);
}
fs.unlink(backupPath, () => {});
callback(null, data);
return resolve(data);
})
})
})
}
}
}