]>
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 | ||
47564bbe C |
28 | function isBooleanValid (value: string) { |
29 | return typeof value === 'boolean' || (typeof value === 'string' && validator.isBoolean(value)) | |
30 | } | |
31 | ||
ac81d1a0 C |
32 | function isFileValid ( |
33 | files: { [ fieldname: string ]: Express.Multer.File[] } | Express.Multer.File[], | |
34 | mimeTypeRegex: string, | |
35 | field: string, | |
36 | optional = false | |
37 | ) { | |
38 | // Should have files | |
39 | if (!files) return optional | |
40 | if (isArray(files)) return optional | |
41 | ||
42 | // Should have a file | |
43 | const fileArray = files[ field ] | |
44 | if (!fileArray || fileArray.length === 0) { | |
45 | return optional | |
46 | } | |
47 | ||
48 | // The file should exist | |
49 | const file = fileArray[ 0 ] | |
50 | if (!file || !file.originalname) return false | |
51 | ||
52 | return new RegExp(`^${mimeTypeRegex}$`, 'i').test(file.mimetype) | |
53 | } | |
54 | ||
e4c55619 C |
55 | // --------------------------------------------------------------------------- |
56 | ||
65fcc311 C |
57 | export { |
58 | exists, | |
72c7248b C |
59 | isArray, |
60 | isIdValid, | |
61 | isUUIDValid, | |
62 | isIdOrUUIDValid, | |
47564bbe | 63 | isDateValid, |
ac81d1a0 C |
64 | isBooleanValid, |
65 | isFileValid | |
65fcc311 | 66 | } |