generated from sapphiredev/sapphire-template
-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
DateConstraints.ts
70 lines (60 loc) · 2.51 KB
/
DateConstraints.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { ExpectedConstraintError } from '../lib/errors/ExpectedConstraintError';
import { Result } from '../lib/Result';
import type { IConstraint } from './base/IConstraint';
import { Comparator, equal, greaterThan, greaterThanOrEqual, lessThan, lessThanOrEqual, notEqual } from './util/operators';
export type DateConstraintName = `s.date.${
| 'lessThan'
| 'lessThanOrEqual'
| 'greaterThan'
| 'greaterThanOrEqual'
| 'equal'
| 'notEqual'
| 'valid'
| 'invalid'}`;
function dateComparator(comparator: Comparator, name: DateConstraintName, expected: string, number: number): IConstraint<Date> {
return {
run(input: Date) {
return comparator(input.getTime(), number) //
? Result.ok(input)
: Result.err(new ExpectedConstraintError(name, 'Invalid Date value', input, expected));
}
};
}
export function dateLessThan(value: Date): IConstraint<Date> {
const expected = `expected < ${value.toISOString()}`;
return dateComparator(lessThan, 's.date.lessThan', expected, value.getTime());
}
export function dateLessThanOrEqual(value: Date): IConstraint<Date> {
const expected = `expected <= ${value.toISOString()}`;
return dateComparator(lessThanOrEqual, 's.date.lessThanOrEqual', expected, value.getTime());
}
export function dateGreaterThan(value: Date): IConstraint<Date> {
const expected = `expected > ${value.toISOString()}`;
return dateComparator(greaterThan, 's.date.greaterThan', expected, value.getTime());
}
export function dateGreaterThanOrEqual(value: Date): IConstraint<Date> {
const expected = `expected >= ${value.toISOString()}`;
return dateComparator(greaterThanOrEqual, 's.date.greaterThanOrEqual', expected, value.getTime());
}
export function dateEqual(value: Date): IConstraint<Date> {
const expected = `expected === ${value.toISOString()}`;
return dateComparator(equal, 's.date.equal', expected, value.getTime());
}
export function dateNotEqual(value: Date): IConstraint<Date> {
const expected = `expected !== ${value.toISOString()}`;
return dateComparator(notEqual, 's.date.notEqual', expected, value.getTime());
}
export const dateInvalid: IConstraint<Date> = {
run(input: Date) {
return Number.isNaN(input.getTime()) //
? Result.ok(input)
: Result.err(new ExpectedConstraintError('s.date.invalid', 'Invalid Date value', input, 'expected === NaN'));
}
};
export const dateValid: IConstraint<Date> = {
run(input: Date) {
return Number.isNaN(input.getTime()) //
? Result.err(new ExpectedConstraintError('s.date.valid', 'Invalid Date value', input, 'expected !== NaN'))
: Result.ok(input);
}
};