Ensure proper error handling when processing of file fails

This commit is contained in:
Nachtalb 2021-04-13 20:39:45 +02:00
parent c2c66031c0
commit 89390b3fc5
No known key found for this signature in database
GPG key ID: E48DF13C07055D92

View file

@ -148,6 +148,19 @@ class Uploader {
} }
}; };
const successfullCompletion = () => {
doneCallback();
if (!uploadUrl) {
return res.status(400).json({error: "Missing file"});
}
// upload was done, send the generated file url to the client
res.status(200).json({
url: uploadUrl,
});
};
const abortWithError = (err) => { const abortWithError = (err) => {
doneCallback(); doneCallback();
@ -214,10 +227,6 @@ class Uploader {
return abortWithError(err); return abortWithError(err);
} }
// Open a file stream for writing
streamWriter = fs.createWriteStream(destPath);
streamWriter.on("error", abortWithError);
busboyInstance.on("file", (fieldname, fileStream, filename, encoding, contentType) => { busboyInstance.on("file", (fieldname, fileStream, filename, encoding, contentType) => {
uploadUrl = `${randomName}/${encodeURIComponent(filename)}`; uploadUrl = `${randomName}/${encodeURIComponent(filename)}`;
@ -245,40 +254,35 @@ class Uploader {
}); });
if (isImage) { if (isImage) {
const chunks = []; let sharpInstance = sharp({
fileStream animated: true,
.on("data", (chunk) => { pages: -1,
chunks.push(chunk); sequentialRead: true,
}) });
.on("end", () => {
sharp(Buffer.concat(chunks), { sharpInstance
animated: true, .rotate() // auto-orient based on the EXIF Orientation tag
pages: -1, .toFile(destPath, (err) => {
sequentialRead: true, // Removes metadata by default https://sharp.pixelplumbing.com/api-output#tofile if no `withMetadata` is present
}) if (err) {
.rotate() // auto-orient based on the EXIF Orientation tag abortWithError(err);
.toFile(destPath) // Removes metadata by default https://sharp.pixelplumbing.com/api-output#tofile } else {
.catch(abortWithError); successfullCompletion();
}
}); });
fileStream.pipe(sharpInstance);
} else { } else {
// Open a file stream for writing
streamWriter = fs.createWriteStream(destPath);
streamWriter.on("error", abortWithError);
streamWriter.on("finish", successfullCompletion);
// Attempt to write the stream to file // Attempt to write the stream to file
fileStream.pipe(streamWriter); fileStream.pipe(streamWriter);
} }
}); });
busboyInstance.on("finish", () => {
doneCallback();
if (!uploadUrl) {
return res.status(400).json({error: "Missing file"});
}
// upload was done, send the generated file url to the client
res.status(200).json({
url: uploadUrl,
});
});
// pipe request body to busboy for processing // pipe request body to busboy for processing
return req.pipe(busboyInstance); return req.pipe(busboyInstance);
} }