From 92768f6a07629e2250e59b2e2326f10128f6c56f Mon Sep 17 00:00:00 2001 From: IshavSohal Date: Tue, 11 Feb 2025 17:01:04 -0500 Subject: [PATCH] delete product zip file upon cancelling load --- server/index.js | 44 ++++++++++++++++++++++++++++---------------- 1 file changed, 28 insertions(+), 16 deletions(-) diff --git a/server/index.js b/server/index.js index a4b19e310..7ec2a1c13 100644 --- a/server/index.js +++ b/server/index.js @@ -176,7 +176,13 @@ app.route(ROUTE_PREFIX + '/retrieve/:id/:hash').get(function (req, res, next) { const PRODUCT_PATH = `${TARGET_PATH}/${req.params.id}`; const uploadLocation = `${UPLOAD_PATH}/${req.params.id}-outgoing.zip`; const commitHash = req.params.hash; + let isRequestAborted = false; + req.on('error', (err) => { + if (err.message === 'aborted') { + isRequestAborted = true; + } + }); // Check if the product exists. if ( fs.access(PRODUCT_PATH, async (error) => { @@ -212,29 +218,35 @@ app.route(ROUTE_PREFIX + '/retrieve/:id/:hash').get(function (req, res, next) { } const output = fs.createWriteStream(uploadLocation); + // This event listener is fired when the write stream has finished. This means that the // ZIP file should be correctly populated. Now, we can set the correct headers and send the // ZIP file to the client. output.on('close', () => { - res.writeHead(200, { - 'Content-Type': 'application/zip', - 'Content-disposition': `attachment; filename=${req.params.id}.zip`, - 'Content-Length': archive.pointer() - }); + // Delete the zip file if the product load was cancelled by the user + if (isRequestAborted) { + fs.rm(uploadLocation); + } else { + res.writeHead(200, { + 'Content-Type': 'application/zip', + 'Content-disposition': `attachment; filename=${req.params.id}.zip`, + 'Content-Length': archive.pointer() + }); - const result = fs.createReadStream(uploadLocation).pipe(res); + const result = fs.createReadStream(uploadLocation).pipe(res); - // When the piping is finished, delete the stream and perform any git cleanup. - result.on('finish', async () => { - fs.rm(uploadLocation); + // When the piping is finished, delete the stream and perform any git cleanup. + result.on('finish', async () => { + fs.rm(uploadLocation); - if (commitHash !== 'latest') { - // Since the user has not asked for the latest commit, we need to clean up. - // Go back to the main branch and delete the newly created branch. - await git.checkout(currBranch); - await git.deleteLocalBranch(`version-${commitHash}`); - } - }); + if (commitHash !== 'latest') { + // Since the user has not asked for the latest commit, we need to clean up. + // Go back to the main branch and delete the newly created branch. + await git.checkout(currBranch); + await git.deleteLocalBranch(`version-${commitHash}`); + } + }); + } }); // Write the product data to the ZIP file.