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