1 |
|
2 |
|
3 |
|
4 | 'use strict';
|
5 |
|
6 | const Base = require('./Validator');
|
7 |
|
8 | module.exports = class FileValidator extends Base {
|
9 |
|
10 | constructor (config) {
|
11 | super({
|
12 | imageOnly: false,
|
13 | minSize: 1,
|
14 | maxSize: null,
|
15 | extensions: null,
|
16 | mimeTypes: null,
|
17 | ...config
|
18 | });
|
19 | }
|
20 |
|
21 | getMessage () {
|
22 | return this.createMessage(this.message, 'Invalid file');
|
23 | }
|
24 |
|
25 | getNotImageMessage () {
|
26 | return this.createMessage(this.notImage, 'File is not an image');
|
27 | }
|
28 |
|
29 | getTooSmallMessage () {
|
30 | return this.createMessage(this.tooSmall, 'File size cannot be smaller than {limit}', {
|
31 | limit: [this.minSize, 'bytes']
|
32 | });
|
33 | }
|
34 |
|
35 | getTooBigMessage () {
|
36 | return this.createMessage(this.tooBig, 'File size cannot exceed {limit}', {
|
37 | limit: [this.maxSize, 'bytes']
|
38 | });
|
39 | }
|
40 |
|
41 | getWrongExtensionMessage () {
|
42 | return this.createMessage(this.wrongExtension, 'Only these file extensions are allowed: {extensions}', {
|
43 | extensions: this.extensions.join(', ')
|
44 | });
|
45 | }
|
46 |
|
47 | getWrongMimeTypeMessage () {
|
48 | return this.createMessage(this.wrongMimeType, 'Only these file MIME types are allowed: {mimeTypes}', {
|
49 | mimeTypes: this.mimeTypes.join(', ')
|
50 | });
|
51 | }
|
52 |
|
53 | async validateValue (file) {
|
54 | if (!file || !file.path) {
|
55 | return this.getMessage();
|
56 | }
|
57 | if (this.imageOnly && (!file.mime || file.mime.indexOf('image') !== 0)) {
|
58 | return this.getNotImageMessage();
|
59 | }
|
60 | const stat = await FileHelper.getStat(file.path);
|
61 | if (!stat || !stat.isFile()) {
|
62 | return this.getMessage();
|
63 | }
|
64 | if (this.minSize && file.size < this.minSize) {
|
65 | return this.getTooSmallMessage();
|
66 | }
|
67 | if (this.maxSize && file.size > this.maxSize) {
|
68 | return this.getTooBigMessage();
|
69 | }
|
70 | if (Array.isArray(this.extensions)
|
71 | && (!file.extension || !this.extensions.includes(file.extension.toLowerCase()))) {
|
72 | return this.getWrongExtensionMessage();
|
73 | }
|
74 | if (Array.isArray(this.mimeTypes) && (!file.mime || !this.mimeTypes.includes(file.mime))) {
|
75 | return this.getWrongMimeTypeMessage();
|
76 | }
|
77 | }
|
78 |
|
79 | getParams () {
|
80 | return {
|
81 | imageOnly: this.imageOnly,
|
82 | minSize: this.minSize,
|
83 | maxSize: this.maxSize,
|
84 | extensions: this.extensions,
|
85 | mimeTypes: this.mimeTypes,
|
86 | tooSmall: this.tooSmall,
|
87 | tooBig: this.tooBig,
|
88 | wrongExtension: this.wrongExtension,
|
89 | wrongMimeType: this.wrongMimeType
|
90 | };
|
91 | }
|
92 | };
|
93 |
|
94 | const FileHelper = require('../helper/FileHelper'); |
\ | No newline at end of file |