summaryrefslogtreecommitdiff
path: root/src/api/validator2.ts
blob: ed58f445d3cd317c72cb3d82eef38bafc008c1c6 (plain)
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import * as mongo from 'mongodb';
import hasDuplicates from '../common/has-duplicates';

type CustomValidator<T> = (value: T) => boolean | string;

interface Validator {
	get: () => [any, string];

	required: () => Validator;

	validate: (validator: CustomValidator<any>) => Validator;
}

class ValidatorCore implements Validator {
	value: any;
	error: string;

	constructor() {
		this.value = null;
		this.error = null;
	}

	required() {
		if (this.error === null && this.value === null) {
			this.error = 'required';
		}
		return this;
	}

	get(): [any, string] {
		return [this.value, this.error];
	}

	validate(validator: CustomValidator<any>) {
		if (this.error || this.value === null) return this;
		const result = validator(this.value);
		if (result === false) {
			this.error = 'invalid-format';
		} else if (typeof result == 'string') {
			this.error = result;
		}
		return this;
	}
}

class NumberValidator extends ValidatorCore {
	value: number;
	error: string;

	constructor(value) {
		super();
		if (value === undefined || value === null) {
			this.value = null;
		} else if (!Number.isFinite(value)) {
			this.error = 'must-be-a-number';
		} else {
			this.value = value;
		}
	}

	range(min: number, max: number) {
		if (this.error || this.value === null) return this;
		if (this.value < min || this.value > max) {
			this.error = 'invalid-range';
		}
		return this;
	}

	required() {
		return super.required();
	}

	get(): [number, string] {
		return super.get();
	}

	validate(validator: CustomValidator<number>) {
		return super.validate(validator);
	}
}

const it = (value: any) => ({
	must: {
		be: {
			a: {
				string: 0,
				number: () => new NumberValidator(value),
				boolean: 0,
				set: 0
			},
			an: {
				id: 0,
				array: 0,
				object: 0
			}
		}
	}
});

export default it;

const [n, e] = it(42).must.be.a.number().required().range(10, 70).validate(x => x != 21).get();