2016-03-13 23:49:30 +03:00
|
|
|
// # Backup Database
|
|
|
|
// Provides for backing up the database before making potentially destructive changes
|
2020-04-29 18:44:27 +03:00
|
|
|
const fs = require('fs-extra');
|
2016-03-13 23:49:30 +03:00
|
|
|
|
2020-04-29 18:44:27 +03:00
|
|
|
const path = require('path');
|
|
|
|
const Promise = require('bluebird');
|
2020-05-27 20:47:53 +03:00
|
|
|
const config = require('../../../shared/config');
|
2020-05-28 21:30:23 +03:00
|
|
|
const logging = require('../../../shared/logging');
|
2020-05-28 13:57:02 +03:00
|
|
|
const urlUtils = require('../../../shared/url-utils');
|
2020-04-29 18:44:27 +03:00
|
|
|
const exporter = require('../exporter');
|
2016-03-13 23:49:30 +03:00
|
|
|
|
2020-10-20 01:56:46 +03:00
|
|
|
const writeExportFile = function writeExportFile(exportResult) {
|
2020-04-29 18:44:27 +03:00
|
|
|
const filename = path.resolve(urlUtils.urlJoin(config.get('paths').contentPath, 'data', exportResult.filename));
|
2016-03-13 23:49:30 +03:00
|
|
|
|
2020-11-04 13:55:47 +03:00
|
|
|
return Promise.resolve(fs.writeFile(filename, JSON.stringify(exportResult.data))).return(filename);
|
2016-03-13 23:49:30 +03:00
|
|
|
};
|
|
|
|
|
2019-12-16 14:34:26 +03:00
|
|
|
const readBackup = async (filename) => {
|
2019-12-17 11:08:04 +03:00
|
|
|
const parsedFileName = path.parse(filename);
|
|
|
|
const sanitized = `${parsedFileName.name}${parsedFileName.ext}`;
|
|
|
|
const backupPath = path.resolve(urlUtils.urlJoin(config.get('paths').contentPath, 'data', sanitized));
|
2019-12-16 14:34:26 +03:00
|
|
|
|
|
|
|
const exists = await fs.pathExists(backupPath);
|
|
|
|
|
|
|
|
if (exists) {
|
2020-10-20 01:56:46 +03:00
|
|
|
const backupFile = await fs.readFile(backupPath);
|
|
|
|
return JSON.parse(backupFile);
|
2019-12-16 14:34:26 +03:00
|
|
|
} else {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2016-03-13 23:49:30 +03:00
|
|
|
/**
|
|
|
|
* ## Backup
|
|
|
|
* does an export, and stores this in a local file
|
|
|
|
* @returns {Promise<*>}
|
|
|
|
*/
|
2020-10-20 01:56:46 +03:00
|
|
|
const backup = function backup(options) {
|
2020-05-22 21:22:20 +03:00
|
|
|
logging.info('Creating database backup');
|
2017-08-01 16:27:13 +03:00
|
|
|
options = options || {};
|
2016-03-13 23:49:30 +03:00
|
|
|
|
2020-04-29 18:44:27 +03:00
|
|
|
const props = {
|
2017-08-01 16:27:13 +03:00
|
|
|
data: exporter.doExport(options),
|
|
|
|
filename: exporter.fileName(options)
|
2016-03-13 23:49:30 +03:00
|
|
|
};
|
|
|
|
|
|
|
|
return Promise.props(props)
|
|
|
|
.then(writeExportFile)
|
|
|
|
.then(function successMessage(filename) {
|
2020-05-22 21:22:20 +03:00
|
|
|
logging.info('Database backup written to: ' + filename);
|
2018-01-11 18:03:21 +03:00
|
|
|
return filename;
|
2016-03-13 23:49:30 +03:00
|
|
|
});
|
|
|
|
};
|
|
|
|
|
2019-12-16 11:29:24 +03:00
|
|
|
module.exports = {
|
2019-12-16 14:34:26 +03:00
|
|
|
backup,
|
|
|
|
readBackup
|
2019-12-16 11:29:24 +03:00
|
|
|
};
|