]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/custom-validators/misc.ts
Add hls support on server
[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: string) {
53 if (value && isArray(value) === false) return [ value ]
54
55 return value
56 }
57
58 function isFileValid (
59 files: { [ fieldname: string ]: Express.Multer.File[] } | Express.Multer.File[],
60 mimeTypeRegex: string,
61 field: string,
62 maxSize: number | null,
63 optional = false
64 ) {
65 // Should have files
66 if (!files) return optional
67 if (isArray(files)) return optional
68
69 // Should have a file
70 const fileArray = files[ field ]
71 if (!fileArray || fileArray.length === 0) {
72 return optional
73 }
74
75 // The file should exist
76 const file = fileArray[ 0 ]
77 if (!file || !file.originalname) return false
78
79 // Check size
80 if ((maxSize !== null) && file.size > maxSize) return false
81
82 return new RegExp(`^${mimeTypeRegex}$`, 'i').test(file.mimetype)
83 }
84
85 // ---------------------------------------------------------------------------
86
87 export {
88 exists,
89 isArrayOf,
90 isNotEmptyIntArray,
91 isArray,
92 isIdValid,
93 isUUIDValid,
94 isIdOrUUIDValid,
95 isDateValid,
96 toValueOrNull,
97 isBooleanValid,
98 toIntOrNull,
99 toArray,
100 isFileValid
101 }