-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
visitor.ts
200 lines (167 loc) · 6.47 KB
/
visitor.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
import {
NonNullTypeNode,
ListTypeNode,
ObjectTypeDefinitionNode,
FieldDefinitionNode,
EnumTypeDefinitionNode,
NamedTypeNode,
GraphQLSchema,
InputValueDefinitionNode,
Kind,
GraphQLEnumType,
} from 'graphql';
import {
BaseTypesVisitor,
DeclarationBlock,
wrapWithSingleQuotes,
indent,
ParsedTypesConfig,
transformComment,
getConfigValue,
DeclarationKind,
} from '@graphql-codegen/visitor-plugin-common';
import autoBind from 'auto-bind';
import { FlowPluginConfig } from './config';
import { FlowOperationVariablesToObject } from './flow-variables-to-object';
export interface FlowPluginParsedConfig extends ParsedTypesConfig {
useFlowExactObjects: boolean;
useFlowReadOnlyTypes: boolean;
}
export class FlowVisitor extends BaseTypesVisitor<FlowPluginConfig, FlowPluginParsedConfig> {
constructor(schema: GraphQLSchema, pluginConfig: FlowPluginConfig) {
super(schema, pluginConfig, {
useFlowExactObjects: getConfigValue(pluginConfig.useFlowExactObjects, true),
useFlowReadOnlyTypes: getConfigValue(pluginConfig.useFlowReadOnlyTypes, false),
} as FlowPluginParsedConfig);
autoBind(this);
const enumNames = Object.values(schema.getTypeMap())
.map(type => (type instanceof GraphQLEnumType ? type.name : undefined))
.filter(t => t);
this.setArgumentsTransformer(
new FlowOperationVariablesToObject(this.scalars, this.convertName, null, enumNames, pluginConfig.enumPrefix)
);
this.setDeclarationBlockConfig({
blockWrapper: this.config.useFlowExactObjects ? '|' : '',
});
}
protected _getScalar(name: string): string {
return `$ElementType<Scalars, '${name}'>`;
}
InputValueDefinition(node: InputValueDefinitionNode, key?: number | string, parent?: any): string {
const originalFieldNode = parent[key] as FieldDefinitionNode;
const addOptionalSign = originalFieldNode.type.kind !== Kind.NON_NULL_TYPE;
const comment = transformComment(node.description as any as string, 1);
return comment + indent(`${node.name}${addOptionalSign ? '?' : ''}: ${node.type},`);
}
NamedType(node: NamedTypeNode, key, parent, path, ancestors): string {
return `?${super.NamedType(node, key, parent, path, ancestors)}`;
}
ListType(node: ListTypeNode): string {
return `?${super.ListType(node)}`;
}
NonNullType(node: NonNullTypeNode): string {
const baseValue = super.NonNullType(node);
if (baseValue.startsWith('?')) {
return baseValue.substr(1);
}
return baseValue;
}
FieldDefinition(node: FieldDefinitionNode): string {
const typeString = node.type as any as string;
const namePostfix = typeString.startsWith('?') ? '?' : '';
const comment = transformComment(node.description as any as string, 1);
return comment + indent(`${this.config.useFlowReadOnlyTypes ? '+' : ''}${node.name}${namePostfix}: ${typeString},`);
}
ObjectTypeDefinition(node: ObjectTypeDefinitionNode, key: number | string, parent: any): string {
return super.ObjectTypeDefinition(
{
...node,
interfaces:
node.interfaces && node.interfaces.length > 0
? node.interfaces.map(name => (name as any as string).replace('?', ''))
: ([] as any),
},
key,
parent
);
}
protected _buildTypeImport(identifier: string, source: string): string {
return `import { type ${identifier} } from '${source}';`;
}
protected mergeInterfaces(interfaces: string[], hasOtherFields: boolean): string {
if (!interfaces.length) {
return '';
}
return interfaces.map(i => indent(`...${i}`)).join(',\n') + (hasOtherFields ? ',\n ' : '');
}
appendInterfacesAndFieldsToBlock(block: DeclarationBlock, interfaces: string[], fields: string[]): void {
block.withBlock(
this.mergeInterfaces(interfaces, fields.length > 0) + this.mergeAllFields(fields, interfaces.length > 0)
);
}
protected mergeAllFields(allFields: string[], hasInterfaces: boolean): string {
if (allFields.length === 0) {
return '';
}
if (!hasInterfaces) {
return allFields.join('\n');
}
return `...{${this.config.useFlowExactObjects ? '|' : ''}\n${allFields.map(s => indent(s)).join('\n')}\n ${
this.config.useFlowExactObjects ? '|' : ''
}}`;
}
handleEnumValueMapper(
typeIdentifier: string,
importIdentifier: string | null,
sourceIdentifier: string | null,
sourceFile: string | null
): string[] {
let identifier = sourceIdentifier;
if (sourceIdentifier !== typeIdentifier && !sourceIdentifier.includes(' as ')) {
identifier = `${sourceIdentifier} as ${typeIdentifier}`;
}
return [this._buildTypeImport(identifier, sourceFile)];
}
EnumTypeDefinition(node: EnumTypeDefinitionNode): string {
const typeName = node.name as any as string;
if (this.config.enumValues[typeName] && this.config.enumValues[typeName].sourceFile) {
return null;
}
const enumValuesName = this.convertName(node, {
suffix: 'Values',
useTypesPrefix: this.config.enumPrefix,
});
const enumValues = new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind('const')
.withName(enumValuesName)
.withMethodCall('Object.freeze', true)
.withBlock(
node.values
.map(enumOption => {
const comment = transformComment(enumOption.description as any as string, 1);
const optionName = this.convertName(enumOption, { transformUnderscore: true, useTypesPrefix: false });
let enumValue: string | number = enumOption.name as any;
if (
this.config.enumValues[typeName] &&
this.config.enumValues[typeName].mappedValues &&
typeof this.config.enumValues[typeName].mappedValues[enumValue] !== 'undefined'
) {
enumValue = this.config.enumValues[typeName].mappedValues[enumValue];
}
return comment + indent(`${optionName}: ${wrapWithSingleQuotes(enumValue)}`);
})
.join(', \n')
).string;
const enumType = new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind('type')
.withName(this.convertName(node, { useTypesPrefix: this.config.enumPrefix }))
.withComment(node.description as any as string)
.withContent(`$Values<typeof ${enumValuesName}>`).string;
return [enumValues, enumType].join('\n\n');
}
protected getPunctuation(declarationKind: DeclarationKind): string {
return declarationKind === 'type' ? ',' : ';';
}
}