55 lines
1.2 KiB
TypeScript
Executable File
55 lines
1.2 KiB
TypeScript
Executable File
import { spawn } from "child_process";
|
|
|
|
interface BackupToPathParams {
|
|
destinationPath: string;
|
|
filename: string;
|
|
}
|
|
|
|
export async function backupDatabaseToPath({
|
|
destinationPath,
|
|
filename,
|
|
}: BackupToPathParams): Promise<void> {
|
|
const path = await import("path");
|
|
const fs = await import("fs");
|
|
|
|
const outputFile = path.join(destinationPath, filename);
|
|
|
|
return new Promise((resolve, reject) => {
|
|
const pgDump = spawn(
|
|
"pg_dump",
|
|
[
|
|
"--no-acl",
|
|
"--no-owner",
|
|
"-h",
|
|
process.env.DB_HOST || "localhost",
|
|
"-U",
|
|
process.env.DB_USER || "postgres",
|
|
"-f",
|
|
outputFile,
|
|
process.env.DB_NAME || "dental_db",
|
|
],
|
|
{
|
|
env: {
|
|
...process.env,
|
|
PGPASSWORD: process.env.DB_PASSWORD,
|
|
},
|
|
}
|
|
);
|
|
|
|
let pgError = "";
|
|
|
|
pgDump.stderr.on("data", (d) => (pgError += d.toString()));
|
|
|
|
pgDump.on("close", (code) => {
|
|
if (code !== 0) {
|
|
// clean up partial file if it was created
|
|
try {
|
|
if (fs.existsSync(outputFile)) fs.unlinkSync(outputFile);
|
|
} catch {}
|
|
return reject(new Error(pgError || "pg_dump failed"));
|
|
}
|
|
resolve();
|
|
});
|
|
});
|
|
}
|