-
-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathschema_visitor.ts
More file actions
83 lines (67 loc) · 2.65 KB
/
schema_visitor.ts
File metadata and controls
83 lines (67 loc) · 2.65 KB
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
import type {
Types,
} from '@graphql-codegen/plugin-helpers';
import type {
FieldDefinitionNode,
GraphQLSchema,
InputValueDefinitionNode,
InterfaceTypeDefinitionNode,
ObjectTypeDefinitionNode,
} from 'graphql';
import type { ValidationSchemaPluginConfig } from './config.js';
import type { SchemaVisitor } from './types.js';
import { Visitor } from './visitor.js';
export abstract class BaseSchemaVisitor implements SchemaVisitor {
protected importTypes: string[] = [];
protected importValueTypes: string[] = [];
protected enumDeclarations: string[] = [];
constructor(
protected schema: GraphQLSchema,
protected config: ValidationSchemaPluginConfig,
) {}
abstract importValidationSchema(): string;
buildImports(): string[] {
if (this.config.importFrom && this.importTypes.length > 0) {
const namedImportPrefix = this.config.useTypeImports ? 'type ' : '';
const importValueTypes = [...new Set(this.importValueTypes)];
const importTypes = [...new Set(this.importTypes)]
.filter(type => this.config.useTypeImports !== true || !importValueTypes.includes(type));
const importCore = this.config.schemaNamespacedImportName
? `* as ${this.config.schemaNamespacedImportName}`
: `${namedImportPrefix}{ ${importTypes.join(', ')} }`;
const imports = [this.importValidationSchema()];
if (this.config.schemaNamespacedImportName) {
imports.push(`import ${importCore} from '${this.config.importFrom}'`);
return imports;
}
if (this.config.useTypeImports === true && importValueTypes.length > 0)
imports.push(`import { ${importValueTypes.join(', ')} } from '${this.config.importFrom}'`);
if (importTypes.length > 0)
imports.push(`import ${importCore} from '${this.config.importFrom}'`);
return imports;
}
return [this.importValidationSchema()];
}
abstract initialEmit(): string;
buildOperationDefinitions(_documents: Types.DocumentFile[]): string[] {
return [];
}
createVisitor(scalarDirection: 'input' | 'output' | 'both'): Visitor {
return new Visitor(scalarDirection, this.schema, this.config);
}
protected abstract buildInputFields(
fields: readonly (FieldDefinitionNode | InputValueDefinitionNode)[],
visitor: Visitor,
name: string,
description?: string
): string;
protected buildTypeDefinitionArguments(
node: ObjectTypeDefinitionNode | InterfaceTypeDefinitionNode,
visitor: Visitor,
) {
return visitor.buildArgumentsSchemaBlock(node, (typeName, field) => {
this.importTypes.push(typeName);
return this.buildInputFields(field.arguments ?? [], visitor, typeName);
});
}
}