UNPKG

@adonisjs/bodyparser

Version:

AdonisJs body parser to read and parse HTTP request bodies

103 lines (102 loc) 3.07 kB
"use strict"; /* * @adonisjs/bodyparser * * (c) Harminder Virk <virk@adonisjs.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.SizeValidator = void 0; /// <reference path="../../../adonis-typings/bodyparser.ts" /> const bytes_1 = __importDefault(require("bytes")); /** * Size validator validates the file size */ class SizeValidator { constructor(file) { this.file = file; this.bytesLimit = 0; this.validated = false; } /** * Defining the maximum bytes the file can have */ get maxLimit() { return this.maximumAllowedLimit; } set maxLimit(limit) { if (this.maximumAllowedLimit !== undefined) { throw new Error('Cannot reset sizeLimit after file has been validated'); } this.validated = false; this.maximumAllowedLimit = limit; if (this.maximumAllowedLimit) { this.bytesLimit = typeof this.maximumAllowedLimit === 'string' ? (0, bytes_1.default)(this.maximumAllowedLimit) : this.maximumAllowedLimit; } } /** * Reporting error to the file */ reportError() { this.file.errors.push({ fieldName: this.file.fieldName, clientName: this.file.clientName, message: `File size should be less than ${(0, bytes_1.default)(this.bytesLimit)}`, type: 'size', }); } /** * Validating file size while it is getting streamed. We only mark * the file as `validated` when it's validation fails. Otherwise * we keep re-validating the file as we receive more data. */ validateWhenGettingStreamed() { if (this.file.size > this.bytesLimit) { this.validated = true; this.reportError(); } } /** * We have the final file size after the stream has been consumed. At this * stage we always mark `validated = true`. */ validateAfterConsumed() { this.validated = true; if (this.file.size > this.bytesLimit) { this.reportError(); } } /** * Validate the file size */ validate() { if (this.validated) { return; } /** * Do not attempt to validate when `maximumAllowedLimit` is not * defined. */ if (this.maximumAllowedLimit === undefined) { this.validated = true; return; } if (this.file.state === 'streaming') { this.validateWhenGettingStreamed(); return; } if (this.file.state === 'consumed') { this.validateAfterConsumed(); return; } } } exports.SizeValidator = SizeValidator;