UNPKG

9.59 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.KotlinResolversVisitor = exports.KOTLIN_SCALARS = void 0;
4const visitor_plugin_common_1 = require("@graphql-codegen/visitor-plugin-common");
5const graphql_1 = require("graphql");
6const java_common_1 = require("@graphql-codegen/java-common");
7exports.KOTLIN_SCALARS = {
8 ID: 'Any',
9 String: 'String',
10 Boolean: 'Boolean',
11 Int: 'Int',
12 Float: 'Float',
13};
14class KotlinResolversVisitor extends visitor_plugin_common_1.BaseVisitor {
15 constructor(rawConfig, _schema, defaultPackageName) {
16 super(rawConfig, {
17 enumValues: rawConfig.enumValues || {},
18 listType: rawConfig.listType || 'Iterable',
19 withTypes: rawConfig.withTypes || false,
20 package: rawConfig.package || defaultPackageName,
21 scalars: (0, visitor_plugin_common_1.buildScalarsFromConfig)(_schema, rawConfig, exports.KOTLIN_SCALARS),
22 omitJvmStatic: rawConfig.omitJvmStatic || false,
23 });
24 this._schema = _schema;
25 }
26 getPackageName() {
27 return `package ${this.config.package}\n`;
28 }
29 getEnumValue(enumName, enumOption) {
30 if (this.config.enumValues[enumName] &&
31 typeof this.config.enumValues[enumName] === 'object' &&
32 this.config.enumValues[enumName][enumOption]) {
33 return this.config.enumValues[enumName][enumOption];
34 }
35 return enumOption;
36 }
37 EnumValueDefinition(node) {
38 return (enumName) => {
39 return (0, visitor_plugin_common_1.indent)(`${this.convertName(node, { useTypesPrefix: false, transformUnderscore: true })}("${this.getEnumValue(enumName, node.name.value)}")`);
40 };
41 }
42 EnumTypeDefinition(node) {
43 const comment = (0, visitor_plugin_common_1.transformComment)(node.description, 0);
44 const enumName = this.convertName(node.name);
45 const enumValues = (0, visitor_plugin_common_1.indentMultiline)(node.values.map(enumValue => enumValue(node.name.value)).join(',\n') + ';', 2);
46 return `${comment}enum class ${enumName}(val label: String) {
47${enumValues}
48
49 companion object {
50 ${this.config.omitJvmStatic ? '' : '@JvmStatic'}
51 fun valueOfLabel(label: String): ${enumName}? {
52 return values().find { it.label == label }
53 }
54 }
55}`;
56 }
57 resolveInputFieldType(typeNode) {
58 const innerType = (0, visitor_plugin_common_1.getBaseTypeNode)(typeNode);
59 const schemaType = this._schema.getType(innerType.name.value);
60 const isArray = typeNode.kind === graphql_1.Kind.LIST_TYPE ||
61 (typeNode.kind === graphql_1.Kind.NON_NULL_TYPE && typeNode.type.kind === graphql_1.Kind.LIST_TYPE);
62 let result = null;
63 const nullable = typeNode.kind !== graphql_1.Kind.NON_NULL_TYPE;
64 if ((0, graphql_1.isScalarType)(schemaType)) {
65 if (this.config.scalars[schemaType.name]) {
66 result = {
67 baseType: this.scalars[schemaType.name],
68 typeName: this.scalars[schemaType.name],
69 isScalar: true,
70 isArray,
71 nullable,
72 };
73 }
74 else {
75 result = { isArray, baseType: 'Any', typeName: 'Any', isScalar: true, nullable };
76 }
77 }
78 else if ((0, graphql_1.isInputObjectType)(schemaType)) {
79 const convertedName = this.convertName(schemaType.name);
80 const typeName = convertedName.endsWith('Input') ? convertedName : `${convertedName}Input`;
81 result = {
82 baseType: typeName,
83 typeName,
84 isScalar: false,
85 isArray,
86 nullable,
87 };
88 }
89 else if ((0, graphql_1.isEnumType)(schemaType) || (0, graphql_1.isObjectType)(schemaType)) {
90 result = {
91 isArray,
92 baseType: this.convertName(schemaType.name),
93 typeName: this.convertName(schemaType.name),
94 isScalar: true,
95 nullable,
96 };
97 }
98 else {
99 result = { isArray, baseType: 'Any', typeName: 'Any', isScalar: true, nullable };
100 }
101 if (result) {
102 result.typeName = (0, java_common_1.wrapTypeWithModifiers)(result.typeName, typeNode, this.config.listType);
103 }
104 return result;
105 }
106 buildInputTransfomer(name, inputValueArray) {
107 const classMembers = inputValueArray
108 .map(arg => {
109 const typeToUse = this.resolveInputFieldType(arg.type);
110 const initialValue = this.initialValue(typeToUse.typeName, arg.defaultValue);
111 const initial = initialValue ? ` = ${initialValue}` : typeToUse.nullable ? ' = null' : '';
112 return (0, visitor_plugin_common_1.indent)(`val ${arg.name.value}: ${typeToUse.typeName}${typeToUse.nullable ? '?' : ''}${initial}`, 2);
113 })
114 .join(',\n');
115 let suppress = '';
116 const ctorSet = inputValueArray
117 .map(arg => {
118 const typeToUse = this.resolveInputFieldType(arg.type);
119 const initialValue = this.initialValue(typeToUse.typeName, arg.defaultValue);
120 const fallback = initialValue ? ` ?: ${initialValue}` : '';
121 if (typeToUse.isArray && !typeToUse.isScalar) {
122 suppress = '@Suppress("UNCHECKED_CAST")\n ';
123 return (0, visitor_plugin_common_1.indent)(`args["${arg.name.value}"]${typeToUse.nullable || fallback ? '?' : '!!'}.let { ${arg.name.value} -> (${arg.name.value} as List<Map<String, Any>>).map { ${typeToUse.baseType}(it) } }${fallback}`, 3);
124 }
125 if (typeToUse.isScalar) {
126 return (0, visitor_plugin_common_1.indent)(`args["${arg.name.value}"] as ${typeToUse.typeName}${typeToUse.nullable || fallback ? '?' : ''}${fallback}`, 3);
127 }
128 if (typeToUse.nullable || fallback) {
129 suppress = '@Suppress("UNCHECKED_CAST")\n ';
130 return (0, visitor_plugin_common_1.indent)(`args["${arg.name.value}"]?.let { ${typeToUse.typeName}(it as Map<String, Any>) }${fallback}`, 3);
131 }
132 suppress = '@Suppress("UNCHECKED_CAST")\n ';
133 return (0, visitor_plugin_common_1.indent)(`${typeToUse.typeName}(args["${arg.name.value}"] as Map<String, Any>)`, 3);
134 })
135 .join(',\n');
136 // language=kotlin
137 return `data class ${name}(
138${classMembers}
139) {
140 ${suppress}constructor(args: Map<String, Any>) : this(
141${ctorSet}
142 )
143}`;
144 }
145 buildTypeTransfomer(name, typeValueArray) {
146 const classMembers = typeValueArray
147 .map(arg => {
148 if (!arg.type) {
149 return '';
150 }
151 const typeToUse = this.resolveInputFieldType(arg.type);
152 return (0, visitor_plugin_common_1.indent)(`val ${arg.name.value}: ${typeToUse.typeName}${typeToUse.nullable ? '?' : ''}`, 2);
153 })
154 .join(',\n');
155 // language=kotlin
156 return `data class ${name}(
157${classMembers}
158)`;
159 }
160 initialValue(typeName, defaultValue) {
161 if (defaultValue) {
162 if (defaultValue.kind === 'IntValue' ||
163 defaultValue.kind === 'FloatValue' ||
164 defaultValue.kind === 'BooleanValue') {
165 return `${defaultValue.value}`;
166 }
167 if (defaultValue.kind === 'StringValue') {
168 return `"""${defaultValue.value}""".trimIndent()`;
169 }
170 if (defaultValue.kind === 'EnumValue') {
171 return `${typeName}.${defaultValue.value}`;
172 }
173 if (defaultValue.kind === 'ListValue') {
174 const list = defaultValue.values
175 .map(value => {
176 return this.initialValue(typeName, value);
177 })
178 .join(', ');
179 return `listOf(${list})`;
180 }
181 // Variable
182 // ObjectValue
183 // ObjectField
184 }
185 return undefined;
186 }
187 FieldDefinition(node) {
188 if (node.arguments.length > 0) {
189 const inputTransformer = (typeName) => {
190 const transformerName = `${this.convertName(typeName, { useTypesPrefix: true })}${this.convertName(node.name.value, { useTypesPrefix: false })}Args`;
191 return this.buildInputTransfomer(transformerName, node.arguments);
192 };
193 return { node, inputTransformer };
194 }
195 return { node };
196 }
197 InputObjectTypeDefinition(node) {
198 const convertedName = this.convertName(node);
199 const name = convertedName.endsWith('Input') ? convertedName : `${convertedName}Input`;
200 return this.buildInputTransfomer(name, node.fields);
201 }
202 ObjectTypeDefinition(node) {
203 const name = this.convertName(node);
204 const fields = node.fields;
205 const fieldNodes = [];
206 const argsTypes = [];
207 fields.forEach(({ node, inputTransformer }) => {
208 if (node) {
209 fieldNodes.push(node);
210 }
211 if (inputTransformer) {
212 argsTypes.push(inputTransformer);
213 }
214 });
215 let types = argsTypes.map(f => f(node.name.value)).filter(r => r);
216 if (this.config.withTypes) {
217 types = types.concat([this.buildTypeTransfomer(name, fieldNodes)]);
218 }
219 return types.join('\n');
220 }
221}
222exports.KotlinResolversVisitor = KotlinResolversVisitor;