]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/custom-validators/misc.ts
Add ability to limit videos history size
[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 isNotEmptyIntArray (value: any) {
13 return Array.isArray(value) && value.every(v => validator.isInt('' + v)) && value.length !== 0
14 }
15
16 function isArrayOf (value: any, validator: (value: any) => boolean) {
17 return isArray(value) && value.every(v => validator(v))
18 }
19
20 function isDateValid (value: string) {
21 return exists(value) && validator.isISO8601(value)
22 }
23
24 function isIdValid (value: string) {
25 return exists(value) && validator.isInt('' + value)
26 }
27
28 function isUUIDValid (value: string) {
29 return exists(value) && validator.isUUID('' + value, 4)
30 }
31
32 function isIdOrUUIDValid (value: string) {
33 return isIdValid(value) || isUUIDValid(value)
34 }
35
36 function isBooleanValid (value: any) {
37 return typeof value === 'boolean' || (typeof value === 'string' && validator.isBoolean(value))
38 }
39
40 function toIntOrNull (value: string) {
41 if (value === 'null') return null
42
43 return validator.toInt(value)
44 }
45
46 function toValueOrNull (value: string) {
47 if (value === 'null') return null
48
49 return value
50 }
51
52 function toArray (value: any) {
53 if (value && isArray(value) === false) return [ value ]
54
55 return value
56 }
57
58 function toIntArray (value: any) {
59 if (!value) return []
60 if (isArray(value) === false) return [ validator.toInt(value) ]
61
62 return value.map(v => validator.toInt(v))
63 }
64
65 function isFileValid (
66 files: { [ fieldname: string ]: Express.Multer.File[] } | Express.Multer.File[],
67 mimeTypeRegex: string,
68 field: string,
69 maxSize: number | null,
70 optional = false
71 ) {
72 // Should have files
73 if (!files) return optional
74 if (isArray(files)) return optional
75
76 // Should have a file
77 const fileArray = files[ field ]
78 if (!fileArray || fileArray.length === 0) {
79 return optional
80 }
81
82 // The file should exist
83 const file = fileArray[ 0 ]
84 if (!file || !file.originalname) return false
85
86 // Check size
87 if ((maxSize !== null) && file.size > maxSize) return false
88
89 return new RegExp(`^${mimeTypeRegex}$`, 'i').test(file.mimetype)
90 }
91
92 // ---------------------------------------------------------------------------
93
94 export {
95 exists,
96 isArrayOf,
97 isNotEmptyIntArray,
98 isArray,
99 isIdValid,
100 isUUIDValid,
101 isIdOrUUIDValid,
102 isDateValid,
103 toValueOrNull,
104 isBooleanValid,
105 toIntOrNull,
106 toArray,
107 toIntArray,
108 isFileValid
109 }