Skip to content

Commit

Permalink
feat(db backup): script to take db backups (#168)
Browse files Browse the repository at this point in the history
* feat(db-backup): rebase

fe 126

* feat(db-backup): rebase

* feat(db-backup): rebase

* feat(db-backup): create modules to take backup and delete backups older than a week

fe #126

* feat(db-backup): ammendments

fe #126

* feat(db-backup): ammendments after review

fe #126
  • Loading branch information
elefher authored Sep 24, 2020
1 parent ecd0c1e commit 9574664
Showing 1 changed file with 68 additions and 0 deletions.
68 changes: 68 additions & 0 deletions scripts/db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
require('dotenv').config({ path: __dirname + '/../.env' })
const { exec } = require('child_process')
const fs = require('fs')
const path = require('path')

const backup = path => {
if (!path) {
console.error(
'Usage:\tnode -e \'require("./db.js").backup("/path/to/store/backup/file")',
)
process.exit(1)
}

const fileName = `${path}/${new Date()
.toISOString()
.replace(/T/, '_')
.replace(/\..+/, '')}_standup_db_backup.archive`

const command = `docker exec standup-mongo-db sh -c "exec mongodump -u ${process.env.DB_USERNAME} -p ${process.env.DB_PASSWORD} -d ${process.env.DB_NAME} --archive" > ${fileName}`

exec(command, err => {
if (err) {
console.error(err)
}
})
}

const deleteOldBackups = filePath => {
if (!filePath) {
console.error(
'Usage:\tnode -e \'require("./db.js").deleteOldBackups("/path/to/store/backup/file")',
)
process.exit(1)
}

fs.readdir(filePath, function (err, files) {
if (err) {
console.error(err)
return
}

files.forEach(fileName => {
if (!fileName.includes('.archive')) {
return
}

fs.stat(path.join(filePath, fileName), function (err, stat) {
if (err) {
return console.error(err)
}

const now = new Date().getTime()
const oneWeek = new Date(stat.ctime).getTime() + 604800000

if (now > oneWeek) {
return fs.unlink(path.join(filePath, fileName), function (err) {
if (err) {
return console.error(err)
}
console.log('successfully deleted')
})
}
})
})
})
}

module.exports = { backup, deleteOldBackups }

0 comments on commit 9574664

Please sign in to comment.