I am trying to validate incomig request size and wrote such middleware:
@Injectable()
export class RequestLimitMiddleware implements NestMiddleware {
requestSizeLimitBytes: number;
constructor(
private readonly configService: ConfigService,
) {
this.requestSizeLimitBytes = configService.getRequestSizeLimitBytes();
}
async use(req: RequestWithByteCounter, res: Response, next: NextFunction) {
if (!req.requestTotalBytes) {
req.requestTotalBytes = 0;
}
req.on('data', (chunk) => {
req.requestTotalBytes += chunk.length;
console.log('DATA LENGTH:', chunk.length);
if (req.requestTotalBytes > this.requestSizeLimitBytes && !req.limitPassed) {
// throw new HttpException('TOO MUCH', 413);
req.emit('error', new HttpException('TOO MUCH', 413));
}
});
next();
}
}
The problem is: I don't understand how to propagate exception and terminate the whole request stream chain properly from on-data event. Ideally Error should be passed to nest.js ExceptionFilter.
Solution should work both for multipart and singlepart requests.
I tried also pipes and guards, but it seems that they don't provide special tools for my task.
What could you advise? Maybe different approach?