]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/custom-validators/misc.ts
Add user notification base code
[github/Chocobozzz/PeerTube.git] / server / helpers / custom-validators / misc.ts
1 import 'multer'
2 import * as validator from 'validator'
3
4 function exists (value: any) {
5 return value !== undefined && value !== null
6 }
7
8 function isArray (value: any) {
9 return Array.isArray(value)
10 }
11
12 function isIntArray (value: any) {
13 return Array.isArray(value) && value.every(v => validator.isInt('' + v))
14 }
15
16 function isDateValid (value: string) {
17 return exists(value) && validator.isISO8601(value)
18 }
19
20 function isIdValid (value: string) {
21 return exists(value) && validator.isInt('' + value)
22 }
23
24 function isUUIDValid (value: string) {
25 return exists(value) && validator.isUUID('' + value, 4)
26 }
27
28 function isIdOrUUIDValid (value: string) {
29 return isIdValid(value) || isUUIDValid(value)
30 }
31
32 function isBooleanValid (value: any) {
33 return typeof value === 'boolean' || (typeof value === 'string' && validator.isBoolean(value))
34 }
35
36 function toIntOrNull (value: string) {
37 if (value === 'null') return null
38
39 return validator.toInt(value)
40 }
41
42 function toValueOrNull (value: string) {
43 if (value === 'null') return null
44
45 return value
46 }
47
48 function toArray (value: string) {
49 if (value && isArray(value) === false) return [ value ]
50
51 return value
52 }
53
54 function isFileValid (
55 files: { [ fieldname: string ]: Express.Multer.File[] } | Express.Multer.File[],
56 mimeTypeRegex: string,
57 field: string,
58 maxSize: number | null,
59 optional = false
60 ) {
61 // Should have files
62 if (!files) return optional
63 if (isArray(files)) return optional
64
65 // Should have a file
66 const fileArray = files[ field ]
67 if (!fileArray || fileArray.length === 0) {
68 return optional
69 }
70
71 // The file should exist
72 const file = fileArray[ 0 ]
73 if (!file || !file.originalname) return false
74
75 // Check size
76 if ((maxSize !== null) && file.size > maxSize) return false
77
78 return new RegExp(`^${mimeTypeRegex}$`, 'i').test(file.mimetype)
79 }
80
81 // ---------------------------------------------------------------------------
82
83 export {
84 exists,
85 isIntArray,
86 isArray,
87 isIdValid,
88 isUUIDValid,
89 isIdOrUUIDValid,
90 isDateValid,
91 toValueOrNull,
92 isBooleanValid,
93 toIntOrNull,
94 toArray,
95 isFileValid
96 }