1 | import { normalizeAvoidOptionals, OperationVariablesToObject, } from '@graphql-codegen/visitor-plugin-common';
|
2 | import { Kind } from 'graphql';
|
3 | export class TypeScriptOperationVariablesToObject extends OperationVariablesToObject {
|
4 | constructor(_scalars, _convertName, _avoidOptionals, _immutableTypes, _namespacedImportName = null, _enumNames = [], _enumPrefix = true, _enumSuffix = true, _enumValues = {}, _applyCoercion = false, _directiveArgumentAndInputFieldMappings = {}, _maybeType = 'Maybe') {
|
5 | super(_scalars, _convertName, _namespacedImportName, _enumNames, _enumPrefix, _enumSuffix, _enumValues, _applyCoercion, _directiveArgumentAndInputFieldMappings);
|
6 | this._avoidOptionals = _avoidOptionals;
|
7 | this._immutableTypes = _immutableTypes;
|
8 | this._maybeType = _maybeType;
|
9 | }
|
10 | clearOptional(str) {
|
11 | const prefix = this._namespacedImportName ? `${this._namespacedImportName}.` : '';
|
12 | const rgx = new RegExp(`^${this.wrapMaybe(`(.*?)`)}$`, 'i');
|
13 | if (str.startsWith(`${prefix}${this._maybeType}`)) {
|
14 | return str.replace(rgx, '$1');
|
15 | }
|
16 | return str;
|
17 | }
|
18 | wrapAstTypeWithModifiers(baseType, typeNode, applyCoercion = false) {
|
19 | if (typeNode.kind === Kind.NON_NULL_TYPE) {
|
20 | const type = this.wrapAstTypeWithModifiers(baseType, typeNode.type, applyCoercion);
|
21 | return this.clearOptional(type);
|
22 | }
|
23 | if (typeNode.kind === Kind.LIST_TYPE) {
|
24 | const innerType = this.wrapAstTypeWithModifiers(baseType, typeNode.type, applyCoercion);
|
25 | const listInputCoercionExtension = applyCoercion ? ` | ${innerType}` : '';
|
26 | return this.wrapMaybe(`${this._immutableTypes ? 'ReadonlyArray' : 'Array'}<${innerType}>${listInputCoercionExtension}`);
|
27 | }
|
28 | return this.wrapMaybe(baseType);
|
29 | }
|
30 | formatFieldString(fieldName, isNonNullType, hasDefaultValue) {
|
31 | return `${fieldName}${this.getAvoidOption(isNonNullType, hasDefaultValue) ? '?' : ''}`;
|
32 | }
|
33 | formatTypeString(fieldType, isNonNullType, hasDefaultValue) {
|
34 | if (!hasDefaultValue && isNonNullType) {
|
35 | return this.clearOptional(fieldType);
|
36 | }
|
37 | return fieldType;
|
38 | }
|
39 | wrapMaybe(type) {
|
40 | const prefix = this._namespacedImportName ? `${this._namespacedImportName}.` : '';
|
41 | return `${prefix}${this._maybeType}${type ? `<${type}>` : ''}`;
|
42 | }
|
43 | getAvoidOption(isNonNullType, hasDefaultValue) {
|
44 | const options = normalizeAvoidOptionals(this._avoidOptionals);
|
45 | return ((options.object || !options.defaultValue) && hasDefaultValue) || (!options.object && !isNonNullType);
|
46 | }
|
47 | getPunctuation() {
|
48 | return ';';
|
49 | }
|
50 | }
|