74 lines
2.0 KiB
TypeScript
74 lines
2.0 KiB
TypeScript
import fs from "fs";
|
|
import path from "path";
|
|
import _ from "lodash";
|
|
import { DSQL_DATASQUIREL_BACKUPS } from "../../../../types/dsql";
|
|
import { APIResponseObject } from "../../../../types";
|
|
import grabDirNames from "../../../../utils/backend/names/grab-dir-names";
|
|
import { NextApiResponse } from "next";
|
|
import { execSync } from "child_process";
|
|
|
|
type Params = {
|
|
backup: DSQL_DATASQUIREL_BACKUPS;
|
|
res: NextApiResponse;
|
|
};
|
|
|
|
export default async function downloadBackup({
|
|
backup,
|
|
res,
|
|
}: Params): Promise<APIResponseObject> {
|
|
try {
|
|
const { mainBackupDir, userBackupDir, tempBackupExportName } =
|
|
grabDirNames({
|
|
userId: backup.user_id,
|
|
});
|
|
|
|
if (backup.user_id && !userBackupDir) {
|
|
return {
|
|
success: false,
|
|
msg: `Error grabbing user backup directory`,
|
|
};
|
|
}
|
|
|
|
if (!backup.uuid) {
|
|
return {
|
|
success: false,
|
|
msg: `No UUID found for backup`,
|
|
};
|
|
}
|
|
|
|
const allBackupsDir =
|
|
backup.user_id && userBackupDir ? userBackupDir : mainBackupDir;
|
|
|
|
const targetBackupDir = path.join(allBackupsDir, backup.uuid);
|
|
|
|
const zipFilesCmd = execSync(
|
|
`tar -cJf ${tempBackupExportName} ${backup.uuid}`,
|
|
{
|
|
cwd: allBackupsDir,
|
|
}
|
|
);
|
|
|
|
const exportFilePath = path.join(allBackupsDir, tempBackupExportName);
|
|
|
|
const readStream = fs.createReadStream(exportFilePath);
|
|
readStream.pipe(res);
|
|
|
|
readStream.on("end", () => {
|
|
console.log("Pipe Complete!");
|
|
setTimeout(() => {
|
|
execSync(`rm -f ${tempBackupExportName}`, {
|
|
cwd: allBackupsDir,
|
|
});
|
|
}, 1000);
|
|
});
|
|
|
|
return { success: true };
|
|
} catch (error: any) {
|
|
return {
|
|
success: false,
|
|
msg: `Failed to write backup files`,
|
|
error: error.message,
|
|
};
|
|
}
|
|
}
|