I’m on the process of making a filter based off evaluating a file’s signature obtained via a file’s buffer provided by Multer. I know Multer provides the MIME type, but I also have to check wether the file is actually of that MIME type via some other ways of validation.
Because of that, my steps are:
- Temporarily store the request’s files in Multer’s memoryStorage() to get the buffer, then
- Filter the valid files
- Append those valid files and other information I need for a newly made FormData
- Make a POST request to the other endpoint(“/upload”) with the new FormData
- Store files in the cloud with Multer
PROBLEM IS: Once I force some error on the second endpoint, the process ends up on a loop. The error is detected, however I cannot return any HTTP code as a response to the first endpoint!
First endpoint:
/* NOTE: storeInMemory.array("files") stores in memory the files' buffer information, which
/* are needed in order to work with validating the files! */
app.post("/filesUpload", storeInMemory.array("files"), async (req, res) => {
const files = req.files;
/* this array stores the items i have to upload */
let uploadArray = [];
/* filter only the items i actually need to upload */
for (const item of files) {
/*-- some filter logic --*/
uploadArray.push(item);
}
/* create new FormData to store the actual files i have to upload -
/* as multer works with http a new formdata has to be created, so i can make a call to another endpoint */
let form = new FormData();
form.append("someData", req.body["someData"]);
/* append the files to the form i'll use to upload later */
uploadArray.forEach((item) => {
form.append("files", item.buffer, item.originalname);
});
try {
const postUrl = process.env.MY_URL + "/upload";
const myHeaders = { headers: { 'Content-Type': `multipart/form-data; boundary=${form._boundary}` } };
/* Request to other endpoint */
let uploadResult = await axios.post(postUrl, form, myHeaders);
if (uploadResult.status == 200) return res.send(uploadResult).status(200);
/* PROBLEM HERE: this is the point the program never gets to and i need it to */
else {
return res.send(uploadResult).status(500);
}
}
catch (error) {
console.error("Unpredicted error occurred: ", error);
return res.send(error)
}
});
Second endpoint:
app.post("/upload", async (req, res) => {
try {
await new Promise((resolve, reject) => {
/* upload the files to cloud */
uploadOnCloud.array("files")(req, res, (err) => {
if (err) {
console.error("Error happened successfully!", err)
return reject(err);
}
else
return resolve();
});
});
/* If no err detected, ends with 200 */
res.sendStatus(200);
}
catch (error) {
/* PROBLEM: can neither set status, nor anything else */
res.status(500).send(error.message);
}
});
What could be wrong here?
easy_to_feel_dumb is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.