-
Notifications
You must be signed in to change notification settings - Fork 13
/
base-type.ts
76 lines (67 loc) · 2.27 KB
/
base-type.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
import {
ClientMetadata, DataTypeFieldConfig, xLuceneTypeConfig, indexedRequiredFieldTypes
} from '@terascope/types';
import { castArray } from '@terascope/utils';
import { GraphQLType, TypeESMapping } from '../interfaces';
import { formatGQLComment } from '../graphql-helper';
export interface IBaseType {
new(field: string, config: DataTypeFieldConfig): BaseType;
}
export type ToGraphQLOptions = {
typeName?: string;
isInput?: boolean;
includePrivate?: boolean;
useSnakeCase?: boolean;
};
export default abstract class BaseType {
readonly field: string;
readonly config: DataTypeFieldConfig;
readonly version: number;
constructor(field: string, config: DataTypeFieldConfig, version = 1) {
this.version = version;
this.field = field;
this.config = config;
}
protected _validateESMapping() {
if (this.config.indexed === false) {
if (this.config.type in indexedRequiredFieldTypes) {
throw new Error(`${this.config.type} is required to be indexed`);
}
}
}
abstract toESMapping(config: ClientMetadata): TypeESMapping;
abstract toGraphQL(options?: ToGraphQLOptions): GraphQLType;
abstract toXlucene(): xLuceneTypeConfig;
protected _formatGql(
type: string,
customType?: string|(string[])
): GraphQLType {
const desc = this.config.description;
if (this.config.array) {
return {
type: formatGQLType(`${this.field}: [${type}]`, desc),
customTypes: makeCustomTypes(customType),
};
}
return {
type: formatGQLType(`${this.field}: ${type}`, desc),
customTypes: makeCustomTypes(customType)
};
}
_formatGQLTypeName(typeName: string, isInput?: boolean, inputSuffix = 'Input'): string {
return [
'DT',
typeName,
isInput ? inputSuffix : '',
`V${this.version}`
].join('');
}
}
function makeCustomTypes(customType?: string|(string[])): string[] {
if (!customType?.length) return [];
return castArray(customType);
}
export function formatGQLType(type: string, desc?: string):string {
if (!desc) return type;
return `${formatGQLComment(desc)}\n${type}`;
}