UNPKG

2.56 kBJavaScriptView Raw
1/**
2 * @copyright Copyright (c) 2019 Maxim Khorin <maksimovichu@gmail.com>
3 */
4'use strict';
5
6const Base = require('./FileValidator');
7
8module.exports = class ImageValidator extends Base {
9
10 constructor (config) {
11 super({
12 maxHeight: null,
13 maxWidth: null,
14 minHeight: null,
15 minWidth: null,
16 ...config
17 });
18 }
19
20 getOverHeightMessage () {
21 return this.createMessage(this.overHeight, 'Height cannot be larger than {limit} px', {
22 limit: this.maxHeight
23 });
24 }
25
26 getOverWidthMessage () {
27 return this.createMessage(this.overWidth, 'Width cannot be larger than {limit} px', {
28 limit: this.maxWidth
29 });
30 }
31
32 getUnderHeightMessage () {
33 return this.createMessage(this.underHeight, 'Height cannot be smaller than {limit} px', {
34 limit: this.minHeight
35 });
36 }
37
38 getUnderWidthMessage () {
39 return this.createMessage(this.underWidth, 'Width cannot be smaller than {limit} px', {
40 limit: this.minWidth
41 });
42 }
43
44 async validateValue (file) {
45 return await super.validateValue(file) || await this.validateImage(file);
46 }
47
48 async validateImage (file) {
49 const sharp = require('sharp');
50 try {
51 const image = sharp(file.path);
52 const data = await image.metadata();
53 if (this.minHeight && data.height < data.minHeight) {
54 return this.getUnderHeightMessage();
55 }
56 if (this.minWidth && data.width < this.minWidth) {
57 return this.getUnderWidthMessage();
58 }
59 if (this.maxHeight && data.height > this.maxHeight) {
60 return this.getOverHeightMessage();
61 }
62 if (this.maxWidth && data.width > this.maxWidth) {
63 return this.getOverWidthMessage();
64 }
65 } catch {
66 return this.getNotImageMessage();
67 }
68 }
69
70 getParams () {
71 return Object.assign(super.getParams(), {
72 imageOnly: true,
73 maxHeight: this.maxHeight,
74 maxWidth: this.maxWidth,
75 minHeight: this.minHeight,
76 minWidth: this.minWidth,
77 notImage: this.notImage,
78 overHeight: this.overHeight,
79 overWidth: this.overWidth,
80 underHeight: this.underHeight,
81 underWidth: this.underWidth
82 });
83 }
84};
\No newline at end of file