UNPKG

3.06 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 */
10Object.defineProperty(exports, "__esModule", { value: true });
11exports.ExtensionValidator = void 0;
12/**
13 * Validates the file extension
14 */
15class ExtensionValidator {
16 constructor(file) {
17 this.file = file;
18 this.allowedExtensions = [];
19 this.validated = false;
20 }
21 /**
22 * Update the expected file extensions
23 */
24 get extensions() {
25 return this.allowedExtensions;
26 }
27 set extensions(extnames) {
28 if (this.allowedExtensions && this.allowedExtensions.length) {
29 throw new Error('Cannot update allowed extension names after file has been validated');
30 }
31 this.validated = false;
32 this.allowedExtensions = extnames;
33 }
34 /**
35 * Report error to the file
36 */
37 reportError() {
38 /**
39 * File is invalid, so report the error
40 */
41 const suffix = this.allowedExtensions.length === 1 ? 'is' : 'are';
42 const message = [
43 `Invalid file extension ${this.file.extname}.`,
44 `Only ${this.allowedExtensions.join(', ')} ${suffix} allowed`,
45 ].join(' ');
46 this.file.errors.push({
47 fieldName: this.file.fieldName,
48 clientName: this.file.clientName,
49 message: message,
50 type: 'extname',
51 });
52 }
53 /**
54 * Validating the file in the streaming mode. During this mode
55 * we defer the validation, until we get the file extname.
56 */
57 validateWhenGettingStreamed() {
58 if (!this.file.extname) {
59 return;
60 }
61 this.validated = true;
62 /**
63 * Valid extension type
64 */
65 if (this.allowedExtensions.includes(this.file.extname)) {
66 return;
67 }
68 this.reportError();
69 }
70 /**
71 * Validate the file extension after it has been streamed
72 */
73 validateAfterConsumed() {
74 this.validated = true;
75 /**
76 * Valid extension type
77 */
78 if (this.allowedExtensions.includes(this.file.extname || '')) {
79 return;
80 }
81 this.reportError();
82 }
83 /**
84 * Validate the file
85 */
86 validate() {
87 /**
88 * Do not validate if already validated
89 */
90 if (this.validated) {
91 return;
92 }
93 /**
94 * Do not run validations, when constraints on the extension are not set
95 */
96 if (!Array.isArray(this.allowedExtensions) || this.allowedExtensions.length === 0) {
97 this.validated = true;
98 return;
99 }
100 if (this.file.state === 'streaming') {
101 this.validateWhenGettingStreamed();
102 return;
103 }
104 if (this.file.state === 'consumed') {
105 this.validateAfterConsumed();
106 }
107 }
108}
109exports.ExtensionValidator = ExtensionValidator;