]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/custom-validators/misc.ts
Add patch for angular cli 6
[github/Chocobozzz/PeerTube.git] / server / helpers / custom-validators / misc.ts
CommitLineData
ac81d1a0 1import 'multer'
72c7248b 2import * as validator from 'validator'
fdbda9e3 3
69818c93 4function exists (value: any) {
e4c55619
C
5 return value !== undefined && value !== null
6}
7
69818c93 8function isArray (value: any) {
e4c55619
C
9 return Array.isArray(value)
10}
11
72c7248b
C
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
360329cc 28function isBooleanValid (value: any) {
47564bbe
C
29 return typeof value === 'boolean' || (typeof value === 'string' && validator.isBoolean(value))
30}
31
360329cc
C
32function toIntOrNull (value: string) {
33 if (value === 'null') return null
34
35 return validator.toInt(value)
36}
37
38function toStringOrNull (value: string) {
39 if (value === 'null') return null
40
41 return value
42}
43
ac81d1a0
C
44function isFileValid (
45 files: { [ fieldname: string ]: Express.Multer.File[] } | Express.Multer.File[],
46 mimeTypeRegex: string,
47 field: string,
48 optional = false
49) {
50 // Should have files
51 if (!files) return optional
52 if (isArray(files)) return optional
53
54 // Should have a file
55 const fileArray = files[ field ]
56 if (!fileArray || fileArray.length === 0) {
57 return optional
58 }
59
60 // The file should exist
61 const file = fileArray[ 0 ]
62 if (!file || !file.originalname) return false
63
64 return new RegExp(`^${mimeTypeRegex}$`, 'i').test(file.mimetype)
65}
66
e4c55619
C
67// ---------------------------------------------------------------------------
68
65fcc311
C
69export {
70 exists,
72c7248b
C
71 isArray,
72 isIdValid,
73 isUUIDValid,
74 isIdOrUUIDValid,
47564bbe 75 isDateValid,
360329cc 76 toStringOrNull,
ac81d1a0 77 isBooleanValid,
360329cc 78 toIntOrNull,
ac81d1a0 79 isFileValid
65fcc311 80}