UNPKG

3.07 kBJavaScriptView Raw
1"use strict";
2/*
3 * @adonisjs/bodyparser
4 *
5 * (c) Harminder Virk <virk@adonisjs.com>
6 *
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
9 */
10var __importDefault = (this && this.__importDefault) || function (mod) {
11 return (mod && mod.__esModule) ? mod : { "default": mod };
12};
13Object.defineProperty(exports, "__esModule", { value: true });
14exports.SizeValidator = void 0;
15/// <reference path="../../../adonis-typings/bodyparser.ts" />
16const bytes_1 = __importDefault(require("bytes"));
17/**
18 * Size validator validates the file size
19 */
20class SizeValidator {
21 constructor(file) {
22 this.file = file;
23 this.bytesLimit = 0;
24 this.validated = false;
25 }
26 /**
27 * Defining the maximum bytes the file can have
28 */
29 get maxLimit() {
30 return this.maximumAllowedLimit;
31 }
32 set maxLimit(limit) {
33 if (this.maximumAllowedLimit !== undefined) {
34 throw new Error('Cannot reset sizeLimit after file has been validated');
35 }
36 this.validated = false;
37 this.maximumAllowedLimit = limit;
38 if (this.maximumAllowedLimit) {
39 this.bytesLimit =
40 typeof this.maximumAllowedLimit === 'string'
41 ? (0, bytes_1.default)(this.maximumAllowedLimit)
42 : this.maximumAllowedLimit;
43 }
44 }
45 /**
46 * Reporting error to the file
47 */
48 reportError() {
49 this.file.errors.push({
50 fieldName: this.file.fieldName,
51 clientName: this.file.clientName,
52 message: `File size should be less than ${(0, bytes_1.default)(this.bytesLimit)}`,
53 type: 'size',
54 });
55 }
56 /**
57 * Validating file size while it is getting streamed. We only mark
58 * the file as `validated` when it's validation fails. Otherwise
59 * we keep re-validating the file as we receive more data.
60 */
61 validateWhenGettingStreamed() {
62 if (this.file.size > this.bytesLimit) {
63 this.validated = true;
64 this.reportError();
65 }
66 }
67 /**
68 * We have the final file size after the stream has been consumed. At this
69 * stage we always mark `validated = true`.
70 */
71 validateAfterConsumed() {
72 this.validated = true;
73 if (this.file.size > this.bytesLimit) {
74 this.reportError();
75 }
76 }
77 /**
78 * Validate the file size
79 */
80 validate() {
81 if (this.validated) {
82 return;
83 }
84 /**
85 * Do not attempt to validate when `maximumAllowedLimit` is not
86 * defined.
87 */
88 if (this.maximumAllowedLimit === undefined) {
89 this.validated = true;
90 return;
91 }
92 if (this.file.state === 'streaming') {
93 this.validateWhenGettingStreamed();
94 return;
95 }
96 if (this.file.state === 'consumed') {
97 this.validateAfterConsumed();
98 return;
99 }
100 }
101}
102exports.SizeValidator = SizeValidator;