UNPKG

@graphql-codegen/typescript-operations

Version:

GraphQL Code Generator plugin for generating TypeScript types for GraphQL queries, mutations, subscriptions and fragments

61 lines (60 loc) 2.74 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TypeScriptOperationVariablesToObject = exports.SCALARS = void 0; const visitor_plugin_common_1 = require("@graphql-codegen/visitor-plugin-common"); const graphql_1 = require("graphql"); exports.SCALARS = { ID: 'string | number', String: 'string', Int: 'number', Float: 'number', Boolean: 'boolean', }; const MAYBE_SUFFIX = ' | null'; class TypeScriptOperationVariablesToObject extends visitor_plugin_common_1.OperationVariablesToObject { _avoidOptionals; _immutableTypes; constructor(_scalars, _convertName, _avoidOptionals, _immutableTypes, _namespacedImportName, _enumNames, _enumPrefix, _enumSuffix, _enumValues, _applyCoercion) { super(_scalars, _convertName, _namespacedImportName, _enumNames, _enumPrefix, _enumSuffix, _enumValues, _applyCoercion, {}); this._avoidOptionals = _avoidOptionals; this._immutableTypes = _immutableTypes; } formatFieldString(fieldName, isNonNullType, hasDefaultValue) { return `${fieldName}${this.getAvoidOption(isNonNullType, hasDefaultValue) ? '?' : ''}`; } formatTypeString(fieldType, _isNonNullType, _hasDefaultValue) { return fieldType; } clearOptional(str) { if (str?.endsWith(MAYBE_SUFFIX)) { return (str = str.substring(0, str.length - MAYBE_SUFFIX.length)); } return str; } getAvoidOption(isNonNullType, hasDefaultValue) { const options = this._avoidOptionals; return ((options.object || !options.defaultValue) && hasDefaultValue) || (!options.object && !isNonNullType); } wrapAstTypeWithModifiers(baseType, typeNode, applyCoercion = false) { if (typeNode.kind === graphql_1.Kind.NON_NULL_TYPE) { const type = this.wrapAstTypeWithModifiers(baseType, typeNode.type, applyCoercion); return this.clearOptional(type); } if (typeNode.kind === graphql_1.Kind.LIST_TYPE) { const innerType = this.wrapAstTypeWithModifiers(baseType, typeNode.type, applyCoercion); const listInputCoercionExtension = applyCoercion ? ` | ${innerType}` : ''; return this.wrapMaybe(`${this._immutableTypes ? 'ReadonlyArray' : 'Array'}<${innerType}>${listInputCoercionExtension}`); } return this.wrapMaybe(baseType); } wrapMaybe(type) { return type?.endsWith(MAYBE_SUFFIX) ? type : `${type}${MAYBE_SUFFIX}`; } getScalar(name) { return this._scalars?.[name]?.input ?? exports.SCALARS[name] ?? 'unknown'; } getPunctuation() { return ';'; } } exports.TypeScriptOperationVariablesToObject = TypeScriptOperationVariablesToObject;