Second request hangs after upload fail into filter function
- Dominant language
- JavaScript
- Stars
- 12.1k
- Forks
- 1.1k
- Avg merge
- 8d 2h
- Merged PRs (30d)
- 21
Description
I'm using multer to receive files just to send it to another service, so I'm using memoryStorage. I'm also filtering files by mime type and trying to use a custom error handling because I'm using a middleware error handling as last middleware. So I have the following in code
```typescript
// filter.ts
const fileFilter = (_request: Request, file: Express.Multer.File, callback: FileFilterCallback) => {
const { mimetype } = file;
const isPDF = mimetype === "application/pdf";
const isJPEG = mimetype === "image/jpeg";
const isPNG = mimetype === "image/png";
if (isPDF || isJPEG || isPNG) {
// eslint-disable-next-line unicorn/no-null
callback(null, true);
} else {
logger.warn("Multer Filter - File sent with wrong extension", { mimetype });
callback(new PreconditionFailed("Invalid file type, only documents PDF or images JPEG/PNG is allowed with a maximum size of 5 MB"));
}
};
export default fileFilter;
```
and
```typescript
import fileFilter from "@services/multer/filter";
import buildMulterErrorMessage from "./buildMulterErrorMessage";
const FIVE_MB_IN_BYTES = 5_000_000;
const storage = multer.memoryStorage();
const upload = multer({
storage,
fileFilter,
limits: { fileSize: FIVE_MB_IN_BYTES },
}).fields([
{ name: "FILE_01", maxCount: 1 },
{ name: "FILE_02", maxCount: 1 },
]);
const factory = (request: Request, response: Response, next: NextFunction) => {
upload(request, response, (error) => {
const isMulterError = error instanceof multer.MulterError;
if (isMulterError) {
const errorMessage = buildMulterErrorMessage(error);
return next(new BadRequest(errorMessage));
}
return next(error);
});
};
export default factory ;
```
I call this factory on routes middleware like `app.post('/file', factory, module)` and it works fine, but if we have a error on filter, the PreconditionError is sent as response, and if I retry the request, this second is hanging. It could be any other endpoint on the API. rigth now I have to manually cancel this second and do a third, which works, and so on, it's keeping this on/off behavior.
### Edit 1
I found out that the problem is to throw an error in fileFilter callback function. If I replace that by `callback(null, false)` and throw the error in `next()´ into `upload` function, it does not hang. But in this way I cant figure out if any file was filtered.
### Edit 2
I found out that if in `factoy` function, if I call `next(error)` twice (without `return`) it will send the error to my error handling middleware the first time, and console the error in second time, but by doing this, prevent the second request to hang
Contributor guide
Assessment
This issue has not been assessed yet.