Currently, I am in the process of developing a filter that evaluates a file's signature obtained through a file's buffer provided by Multer. While Multer supplies the MIME type, additional validation methods are required to confirm if the file matches that MIME type.
My approach involves the following steps:
- Temporarily storing the request's files in Multer's memoryStorage() to access the buffer
- Filtering out the valid files
- Appending these valid files and other necessary information to create a new FormData object
- Initiating a POST request to another endpoint ("/upload") with the new FormData
- Storing the files in the cloud using Multer
THE ISSUE: Whenever an error is deliberately triggered at the second endpoint, it results in an infinite loop. Although the error is identified, I am unable to provide any HTTP response code back to the initial endpoint!
Initial endpoint:
// NOTE: storeInMemory.array("files") stores the files' buffer information in memory,
// which is essential for validating the files.
app.post("/filesUpload", storeInMemory.array("files"), async (req, res) => {
const files = req.files;
// Array to hold items requiring upload
let uploadArray = [];
// Filtering only the necessary items for uploading
for (const item of files) {
// -- add filter logic here --
uploadArray.push(item);
}
// Creating a new FormData to contain the required files as multer operates over http
let form = new FormData();
form.append("someData", req.body["someData"]);
// Attaching files to the form for subsequent upload
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}` } };
// Performing a request to another endpoint
let uploadResult = await axios.post(postUrl, form, myHeaders);
if (uploadResult.status == 200) return res.send(uploadResult).status(200);
// ISSUE HERE: This part is never reached, but it needs to be
else {
return res.send(uploadResult).status(500);
}
}
catch (error) {
console.error("Unexpected error occurred: ", error);
return res.send(error)
}
});
Second endpoint:
app.post("/upload", async (req, res) => {
try {
await new Promise((resolve, reject) => {
// Uploading the files to the cloud
uploadOnCloud.array("files")(req, res, (err) => {
if (err) {
console.error("An error occurred successfully!", err);
return reject(err);
}
else
return resolve();
});
});
// Respond with status 200 if no errors detected
res.sendStatus(200);
}
catch (error) {
// PROBLEM: Unable to set status or anything else
res.status(500).send(error.message);
}
});
What could possibly be wrong with this setup?