1 | "use strict";
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 | Object.defineProperty(exports, "__esModule", { value: true });
|
11 | exports.ExtensionValidator = void 0;
|
12 |
|
13 |
|
14 |
|
15 | class ExtensionValidator {
|
16 | constructor(file) {
|
17 | this.file = file;
|
18 | this.allowedExtensions = [];
|
19 | this.validated = false;
|
20 | }
|
21 | |
22 |
|
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 |
|
36 |
|
37 | reportError() {
|
38 | |
39 |
|
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 |
|
55 |
|
56 |
|
57 | validateWhenGettingStreamed() {
|
58 | if (!this.file.extname) {
|
59 | return;
|
60 | }
|
61 | this.validated = true;
|
62 | |
63 |
|
64 |
|
65 | if (this.allowedExtensions.includes(this.file.extname)) {
|
66 | return;
|
67 | }
|
68 | this.reportError();
|
69 | }
|
70 | |
71 |
|
72 |
|
73 | validateAfterConsumed() {
|
74 | this.validated = true;
|
75 | |
76 |
|
77 |
|
78 | if (this.allowedExtensions.includes(this.file.extname || '')) {
|
79 | return;
|
80 | }
|
81 | this.reportError();
|
82 | }
|
83 | |
84 |
|
85 |
|
86 | validate() {
|
87 | |
88 |
|
89 |
|
90 | if (this.validated) {
|
91 | return;
|
92 | }
|
93 | |
94 |
|
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 | }
|
109 | exports.ExtensionValidator = ExtensionValidator;
|