I am uloading image using multer
and then compressing image using gm
. While uploading image, I am checking for file type and if its not image, throwing err to global err handler for skipping image compression. Thrown err is handled by global err handler but cant send response to frontend from the handler. Tried all resources but nothing seems working!
Routing:
router.post(
"/updateProfile",
auth,
upload(uploadUser.single("file")),
compressImages,
(req, res) => {}
Upload middleware:
const imageFilter = (req, file, cb) => {
const allowedExtensions = /(jpg|jpeg|png)$/i;
const allowedMimetypes = /(image\/jpeg|image\/png)$/i;
if (
allowedExtensions.test(path.extname(file.originalname)) &&
allowedMimetypes.test(file.mimetype)
) {
cb(null, true);
} else {
cb(new CustomError("Invalid file type, only .jpeg/.png allowed!", 415));
}
};
const upload = (uploadType) => (req, res, next) => {
uploadType(req, res, (err) => {
if (err) {
return next(err);
}
return next();
});
};
Global err handler:
const errorHandler = (err, req, res, next) => {
if (res.headersSent) {
console.log("headers sent");
return next(err);
}
if (err) {
res.setHeader("Content-Type", "application/json");
return res
.status(err.statusCode || 500)
.json(new ApiResponse(err.message || "Something went wrong!", null));
}
return next(err);
};
app.use(errorHandler);
In
errorHandler
, send a respone only iferr
exists, let it wrap around the rest: