-
Notifications
You must be signed in to change notification settings - Fork 0
/
@built-in-extensions.ts
70 lines (53 loc) · 1.57 KB
/
@built-in-extensions.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 Validator from 'validator';
import {ValidatorExtensions} from './validator';
export interface BuiltInValidatorExtensionContext {
uniqueSetMap?: Map<string, Set<unknown>>;
}
export const builtInExtensions: ValidatorExtensions<BuiltInValidatorExtensionContext> = {
pattern(value, pattern) {
if (typeof value !== 'string') {
return undefined;
}
if (!pattern) {
throw new Error(
'A regular expression pattern is required for extension `@pattern`',
);
}
let regex = new RegExp(pattern);
if (!regex.test(value)) {
return `Value ${JSON.stringify(value)} does not match pattern ${pattern}`;
}
return undefined;
},
uuid(value, version: '3' | '4' | '5' | 'all' | undefined) {
if (typeof value !== 'string') {
return undefined;
}
if (!Validator.isUUID(value, version)) {
return `Value ${JSON.stringify(value)} is not a valid UUID${
version && version !== 'all' ? ` (v${version})` : ''
}`;
}
return undefined;
},
unique(value, group, context, tagUniqueId) {
let groupName = group || 'value';
if (!group) {
group = tagUniqueId;
}
let {uniqueSetMap} = context;
if (!uniqueSetMap) {
uniqueSetMap = context.uniqueSetMap = new Map();
}
let uniqueSet = uniqueSetMap.get(group);
if (!uniqueSet) {
uniqueSet = new Set();
uniqueSetMap.set(group, uniqueSet);
}
if (uniqueSet.has(value)) {
return `Duplicate ${groupName} ${JSON.stringify(value)}`;
}
uniqueSet.add(value);
return undefined;
},
};