]>
Commit | Line | Data |
---|---|---|
ac81d1a0 | 1 | import 'multer' |
72c7248b | 2 | import * as validator from 'validator' |
fdbda9e3 | 3 | |
69818c93 | 4 | function exists (value: any) { |
e4c55619 C |
5 | return value !== undefined && value !== null |
6 | } | |
7 | ||
69818c93 | 8 | function isArray (value: any) { |
e4c55619 C |
9 | return Array.isArray(value) |
10 | } | |
11 | ||
72c7248b C |
12 | function isDateValid (value: string) { |
13 | return exists(value) && validator.isISO8601(value) | |
14 | } | |
15 | ||
16 | function isIdValid (value: string) { | |
17 | return exists(value) && validator.isInt('' + value) | |
18 | } | |
19 | ||
20 | function isUUIDValid (value: string) { | |
21 | return exists(value) && validator.isUUID('' + value, 4) | |
22 | } | |
23 | ||
24 | function isIdOrUUIDValid (value: string) { | |
25 | return isIdValid(value) || isUUIDValid(value) | |
26 | } | |
27 | ||
360329cc | 28 | function isBooleanValid (value: any) { |
47564bbe C |
29 | return typeof value === 'boolean' || (typeof value === 'string' && validator.isBoolean(value)) |
30 | } | |
31 | ||
360329cc C |
32 | function toIntOrNull (value: string) { |
33 | if (value === 'null') return null | |
34 | ||
35 | return validator.toInt(value) | |
36 | } | |
37 | ||
2efd32f6 | 38 | function toValueOrNull (value: string) { |
360329cc C |
39 | if (value === 'null') return null |
40 | ||
41 | return value | |
42 | } | |
43 | ||
d525fc39 C |
44 | function toArray (value: string) { |
45 | if (value && isArray(value) === false) return [ value ] | |
46 | ||
47 | return value | |
48 | } | |
49 | ||
ac81d1a0 C |
50 | function isFileValid ( |
51 | files: { [ fieldname: string ]: Express.Multer.File[] } | Express.Multer.File[], | |
52 | mimeTypeRegex: string, | |
53 | field: string, | |
c1e791ba | 54 | maxSize: number | null, |
ac81d1a0 C |
55 | optional = false |
56 | ) { | |
57 | // Should have files | |
58 | if (!files) return optional | |
59 | if (isArray(files)) return optional | |
60 | ||
61 | // Should have a file | |
62 | const fileArray = files[ field ] | |
63 | if (!fileArray || fileArray.length === 0) { | |
64 | return optional | |
65 | } | |
66 | ||
67 | // The file should exist | |
68 | const file = fileArray[ 0 ] | |
69 | if (!file || !file.originalname) return false | |
70 | ||
0c237b19 | 71 | // Check size |
c1e791ba | 72 | if ((maxSize !== null) && file.size > maxSize) return false |
0c237b19 | 73 | |
ac81d1a0 C |
74 | return new RegExp(`^${mimeTypeRegex}$`, 'i').test(file.mimetype) |
75 | } | |
76 | ||
e4c55619 C |
77 | // --------------------------------------------------------------------------- |
78 | ||
65fcc311 C |
79 | export { |
80 | exists, | |
72c7248b C |
81 | isArray, |
82 | isIdValid, | |
83 | isUUIDValid, | |
84 | isIdOrUUIDValid, | |
47564bbe | 85 | isDateValid, |
2efd32f6 | 86 | toValueOrNull, |
ac81d1a0 | 87 | isBooleanValid, |
360329cc | 88 | toIntOrNull, |
d525fc39 | 89 | toArray, |
ac81d1a0 | 90 | isFileValid |
65fcc311 | 91 | } |