-
Notifications
You must be signed in to change notification settings - Fork 114
/
constraints.ts
51 lines (46 loc) · 1.19 KB
/
constraints.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* This module parses field validations as a constraint and checks
* values against that constraint.
*/
import isNumber from 'lodash/isNumber';
import { ValidationType } from '../types';
export function fromFieldValidations(validations: Record<string, any>[] = []): ValidationType {
const sizeValidation = validations.find(v => 'size' in v);
const size = (sizeValidation && sizeValidation.size) || {};
const min = size.min;
const max = size.max;
if (isNumber(min) && isNumber(max)) {
return {
type: 'min-max',
min,
max
};
} else if (isNumber(min)) {
return {
type: 'min',
min
};
} else if (isNumber(max)) {
return {
type: 'max',
max
};
} else {
return {
type: 'max',
max: 256
};
}
}
export function makeChecker(constraint: ValidationType) {
return function checkConstraint(length: number) {
if (constraint.type === 'max') {
return length <= constraint.max;
} else if (constraint.type === 'min') {
return length >= constraint.min;
} else {
return length >= constraint.min && length <= constraint.max;
}
};
}