#Request stream termination

5 messages · Page 1 of 1 (latest)

weary drum
#

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?

cyan sail
#

next(new HttpException()) should do it, but you need to make sure you don't call next() until after those event callbacks have finished, meaning you'll probably want to call it in req.on('finish'

weary drum
#

Thank you. It works for single part requests but on multipart it fails with en error BadRequestException: Multipart: Unexpected end of form
I am not sure how to debug this problem.

weary drum
#

I was able to achieve desired behaviour with bare busboy implementation.
Is it possible to disable internal MulterModule in Nest.js?

weary drum
#

Sorry for the question, I realized that it wouldn't be injected if I don't use multer interceptors.