2 import * as validator from 'validator'
3 import { sep } from 'path'
5 function exists (value: any) {
6 return value !== undefined && value !== null
9 function isSafePath (p: string) {
11 (p + '').split(sep).every(part => {
12 return [ '..' ].includes(part) === false
16 function isArray (value: any) {
17 return Array.isArray(value)
20 function isNotEmptyIntArray (value: any) {
21 return Array.isArray(value) && value.every(v => validator.isInt('' + v)) && value.length !== 0
24 function isArrayOf (value: any, validator: (value: any) => boolean) {
25 return isArray(value) && value.every(v => validator(v))
28 function isDateValid (value: string) {
29 return exists(value) && validator.isISO8601(value)
32 function isIdValid (value: string) {
33 return exists(value) && validator.isInt('' + value)
36 function isUUIDValid (value: string) {
37 return exists(value) && validator.isUUID('' + value, 4)
40 function isIdOrUUIDValid (value: string) {
41 return isIdValid(value) || isUUIDValid(value)
44 function isBooleanValid (value: any) {
45 return typeof value === 'boolean' || (typeof value === 'string' && validator.isBoolean(value))
48 function toIntOrNull (value: string) {
49 const v = toValueOrNull(value)
51 if (v === null || v === undefined) return v
52 if (typeof v === 'number') return v
54 return validator.toInt('' + v)
57 function toBooleanOrNull (value: any) {
58 const v = toValueOrNull(value)
60 if (v === null || v === undefined) return v
61 if (typeof v === 'boolean') return v
63 return validator.toBoolean('' + v)
66 function toValueOrNull (value: string) {
67 if (value === 'null') return null
72 function toArray (value: any) {
73 if (value && isArray(value) === false) return [ value ]
78 function toIntArray (value: any) {
80 if (isArray(value) === false) return [ validator.toInt(value) ]
82 return value.map(v => validator.toInt(v))
85 function isFileValid (
86 files: { [ fieldname: string ]: Express.Multer.File[] } | Express.Multer.File[],
87 mimeTypeRegex: string,
89 maxSize: number | null,
93 if (!files) return optional
94 if (isArray(files)) return optional
97 const fileArray = files[ field ]
98 if (!fileArray || fileArray.length === 0) {
102 // The file should exist
103 const file = fileArray[ 0 ]
104 if (!file || !file.originalname) return false
107 if ((maxSize !== null) && file.size > maxSize) return false
109 return new RegExp(`^${mimeTypeRegex}$`, 'i').test(file.mimetype)
112 // ---------------------------------------------------------------------------