/
DataType.ts
94 lines (78 loc) · 1.99 KB
/
DataType.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import { passOrThrow, isFunction } from '../util';
import { ComplexDataType } from './ComplexDataType';
export type DataTypeSetup = {
name: string;
description: string;
mock?: () => any;
validate?: () => any;
enforceRequired?: boolean;
defaultValue?: () => any;
enforceIndex?: boolean;
};
export type DataTypeFunction = (
setup: DataTypeSetup,
context?: any,
) => DataType | ComplexDataType;
export class DataType {
name: string;
description: string;
mock?: () => any;
validator?: (value: any, context: any) => any;
enforceRequired?: boolean;
defaultValue?: () => any;
enforceIndex?: boolean;
constructor(setup: DataTypeSetup = {} as DataTypeSetup) {
const {
name,
description,
mock,
validate,
enforceRequired,
defaultValue,
enforceIndex,
} = setup;
passOrThrow(name, () => 'Missing data type name');
passOrThrow(
description,
() => `Missing description for data type '${name}'`,
);
passOrThrow(
isFunction(mock),
() => `'Missing mock function for data type '${name}'`,
);
if (validate) {
passOrThrow(
isFunction(validate),
() => `'Invalid validate function for data type '${name}'`,
);
this.validator = validate;
}
if (defaultValue) {
passOrThrow(
isFunction(defaultValue),
() => `'Invalid defaultValue function for data type '${name}'`,
);
this.defaultValue = defaultValue;
}
this.name = name;
this.description = description;
this.mock = mock;
if (enforceRequired) {
this.enforceRequired = enforceRequired;
}
if (enforceIndex) {
this.enforceIndex = enforceIndex;
}
}
validate = async (value: any, context: any): Promise<void> => {
if (value && this.validator) {
await this.validator(value, context);
}
};
toString(): string {
return this.name;
}
}
export const isDataType = (obj: any): boolean => {
return obj instanceof DataType;
};