Skip to content

Instantly share code, notes, and snippets.

@mushonnip
Last active July 9, 2023 10:33
Show Gist options
  • Save mushonnip/30f187c7a93b1cd5b61f4020f8bea4c2 to your computer and use it in GitHub Desktop.
Save mushonnip/30f187c7a93b1cd5b61f4020f8bea4c2 to your computer and use it in GitHub Desktop.
require("dotenv").config();
const fs = require("fs");
const Client = require("pg").Client;
const winston = require("winston");
const PATH_TO_SOURCE = process.env.PATH_TO_SOURCE;
const PATH_TO_RESTORED = process.env.PATH_TO_RESTORED
const logger = winston.createLogger({
level: "info",
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
transports: [
new winston.transports.File({ filename: "logs/error.log", level: "error" }),
new winston.transports.File({ filename: "logs/combined.log" }),
],
});
const client = new Client({
database: process.env.DB_DATABASE,
host: process.env.DB_HOST,
port: process.env.DB_PORT,
user: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
});
async function beginAutoRestore() {
try {
logger.info("Begin auto restore");
await client.connect();
const files = fs.readdirSync(PATH_TO_SOURCE);
let successCount = 0, failedCount = 0;
for (let i = 0; i < files.length; i++) {
const file = files[i];
const result = await execuleSql(file);
if (result) {
successCount++;
} else {
failedCount++;
}
}
client.end();
let result = {
"success": successCount,
"failed": failedCount,
"total": successCount + failedCount
};
return result;
} catch (err) {
console.log(err);
client.end();
throw err;
}
}
async function execuleSql(file) {
try {
await client.query("BEGIN");
const queryText = fs.readFileSync(`${PATH_TO_SOURCE}/${file}`, "utf8");
await client.query(queryText);
await client.query("COMMIT");
logger.info(`File ${file} restored`);
fs.copyFileSync(`${PATH_TO_SOURCE}/${file}`, `${PATH_TO_RESTORED}/${file}`);
fs.unlinkSync(`${PATH_TO_SOURCE}/${file}`);
return true
} catch (error) {
await client.query("ROLLBACK");
logger.error(`File ${file} failed to restore, ${error}`);
return false;
}
}
async function main() {
const result = await beginAutoRestore();
console.log("Selesai, ", result);
process.exit(1)
}
function checkDirectoryReadWritePermission(directoryPath) {
try {
// Check if the directory is readable
fs.accessSync(directoryPath, fs.constants.R_OK);
// Check if the directory is writable
fs.accessSync(directoryPath, fs.constants.W_OK);
// If both checks pass, return true
return true;
} catch (err) {
console.log(err);
// If either check fails, return false
return false;
}
}
if (checkDirectoryReadWritePermission(PATH_TO_RESTORED) && checkDirectoryReadWritePermission(PATH_TO_SOURCE)) {
main();
} else {
console.log("Permission denied");
process.exit(1);
}
@mushonnip
Copy link
Author

DB_HOST=localhost
DB_PORT=5432
DB_USERNAME=postgres
DB_PASSWORD=postgres
DB_DATABASE=prj_margono

PATH_TO_SOURCE="./manual"
PATH_TO_RESTORED="./restored-manual"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment