graphql#isCompositeType TypeScript Examples

The following examples show how to use graphql#isCompositeType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: helpers.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
fieldTypeEnum(type: GraphQLType, structName: string): string {
    if (isNonNullType(type)) {
      return `.nonNull(${this.fieldTypeEnum(type.ofType, structName)})`;
    } else if (isListType(type)) {
      return `.list(${this.fieldTypeEnum(type.ofType, structName)})`;
    } else if (type instanceof GraphQLScalarType) {
      return `.scalar(${this.typeNameForScalarType(type)}.self)`;
    } else if (type instanceof GraphQLEnumType) {
      return `.scalar(${type.name}.self)`;
    } else if (isCompositeType(type)) {
      return `.object(${structName}.selections)`;
    } else {
      throw new Error(`Unknown field type: ${type}`);
    }
  }
Example #2
Source File: helpers.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
// Properties

  propertyFromField(field: Field, namespace?: string): Field & Property & Struct {
    const { responseKey, isConditional } = field;

    const propertyName = isMetaFieldName(responseKey) ? responseKey : camelCase(responseKey);

    const structName = join([namespace, this.structNameForPropertyName(responseKey)], '.');

    let type = field.type;

    if (isConditional && isNonNullType(type)) {
      type = type.ofType;
    }

    const isOptional = !(type instanceof GraphQLNonNull);

    const unmodifiedType = getNamedType(field.type);

    const unmodifiedTypeName = isCompositeType(unmodifiedType) ? structName : unmodifiedType.name;

    const typeName = this.typeNameFromGraphQLType(type, unmodifiedTypeName);

    return Object.assign({}, field, {
      responseKey,
      propertyName,
      typeName,
      structName,
      isOptional,
    });
  }
Example #3
Source File: helpers.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
propertiesForSelectionSet(selectionSet: SelectionSet, namespace?: string): (Field & Property)[] | undefined {
    const properties = collectAndMergeFields(selectionSet, true)
      .filter(field => field.name !== '__typename')
      .map(field => this.propertyFromField(field, namespace));

    // If we're not merging in fields from fragment spreads, there is no guarantee there will a generated
    // type for a composite field, so to avoid compiler errors we skip the initializer for now.
    if (
      selectionSet.selections.some(selection => selection.kind === 'FragmentSpread') &&
      properties.some(property => isCompositeType(getNamedType(property.type)))
    ) {
      return undefined;
    }

    return properties;
  }
Example #4
Source File: codeGeneration.ts    From amplify-codegen with Apache License 2.0 5 votes vote down vote up
propertyAssignmentForField(field: { responseKey: string; propertyName: string; type: GraphQLType }) {
    const { responseKey, propertyName, type } = field;
    const valueExpression = isCompositeType(getNamedType(type))
      ? this.helpers.mapExpressionForType(type, identifier => `${identifier}.snapshot`, escapeIdentifierIfNeeded(propertyName))
      : escapeIdentifierIfNeeded(propertyName);
    return `"${responseKey}": ${valueExpression}`;
  }
Example #5
Source File: codeGeneration.ts    From amplify-codegen with Apache License 2.0 5 votes vote down vote up
propertyDeclarationForField(field: Field & Property) {
    const { responseKey, propertyName, typeName, type, isOptional } = field;

    const unmodifiedFieldType = getNamedType(type);

    this.printNewlineIfNeeded();

    this.comment(field.description);
    this.deprecationAttributes(field.isDeprecated, field.deprecationReason);

    this.printOnNewline(`public var ${escapeIdentifierIfNeeded(propertyName)}: ${typeName}`);
    this.withinBlock(() => {
      if (isCompositeType(unmodifiedFieldType)) {
        const structName = escapeIdentifierIfNeeded(this.helpers.structNameForPropertyName(propertyName));

        if (isList(type)) {
          this.printOnNewline('get');
          this.withinBlock(() => {
            const snapshotTypeName = this.helpers.typeNameFromGraphQLType(type, 'Snapshot', false);
            let getter;
            if (isOptional) {
              getter = `return (snapshot["${responseKey}"] as? ${snapshotTypeName})`;
            } else {
              getter = `return (snapshot["${responseKey}"] as! ${snapshotTypeName})`;
            }
            getter += this.helpers.mapExpressionForType(type, identifier => `${structName}(snapshot: ${identifier})`);
            this.printOnNewline(getter);
          });
          this.printOnNewline('set');
          this.withinBlock(() => {
            let newValueExpression = this.helpers.mapExpressionForType(type, identifier => `${identifier}.snapshot`, 'newValue');
            this.printOnNewline(`snapshot.updateValue(${newValueExpression}, forKey: "${responseKey}")`);
          });
        } else {
          this.printOnNewline('get');
          this.withinBlock(() => {
            if (isOptional) {
              this.printOnNewline(`return (snapshot["${responseKey}"] as? Snapshot).flatMap { ${structName}(snapshot: $0) }`);
            } else {
              this.printOnNewline(`return ${structName}(snapshot: snapshot["${responseKey}"]! as! Snapshot)`);
            }
          });
          this.printOnNewline('set');
          this.withinBlock(() => {
            let newValueExpression;
            if (isOptional) {
              newValueExpression = 'newValue?.snapshot';
            } else {
              newValueExpression = 'newValue.snapshot';
            }
            this.printOnNewline(`snapshot.updateValue(${newValueExpression}, forKey: "${responseKey}")`);
          });
        }
      } else {
        this.printOnNewline('get');
        this.withinBlock(() => {
          if (isOptional) {
            this.printOnNewline(`return snapshot["${responseKey}"] as? ${typeName.slice(0, -1)}`);
          } else {
            this.printOnNewline(`return snapshot["${responseKey}"]! as! ${typeName}`);
          }
        });
        this.printOnNewline('set');
        this.withinBlock(() => {
          this.printOnNewline(`snapshot.updateValue(newValue, forKey: "${responseKey}")`);
        });
      }
    });
  }
Example #6
Source File: codeGeneration.ts    From amplify-codegen with Apache License 2.0 5 votes vote down vote up
export function propertyFromField(
  context: LegacyCompilerContext,
  field: {
    name?: string;
    type: GraphQLType;
    fields?: any[];
    responseName?: string;
    description?: Maybe<string>;
    fragmentSpreads?: any;
    inlineFragments?: LegacyInlineFragment[];
    fieldName?: string;
  },
): Property {
  let { name: fieldName, type: fieldType, description, fragmentSpreads, inlineFragments } = field;
  fieldName = fieldName || field.responseName;

  const propertyName = fieldName;

  let property = { fieldName, fieldType, propertyName, description };

  const namedType = getNamedType(fieldType);

  let isNullable = true;
  if (isNonNullType(fieldType)) {
    isNullable = false;
  }

  if (isCompositeType(namedType)) {
    let typeName = namedType.toString();
    let isArray = false;
    let isArrayElementNullable = null;
    if (isListType(fieldType)) {
      isArray = true;
      isArrayElementNullable = !isNonNullType(fieldType.ofType);
    } else if (isNonNullType(fieldType) && isListType(fieldType.ofType)) {
      isArray = true;
      isArrayElementNullable = !isNonNullType(fieldType.ofType.ofType);
    } else if (!isNonNullType(fieldType)) {
      typeName = typeNameFromGraphQLType(context, fieldType, null, isNullable);
    }

    return {
      ...property,
      typeName,
      fields: field.fields,
      isComposite: true,
      fragmentSpreads,
      inlineFragments,
      fieldType,
      isArray,
      isNullable,
      isArrayElementNullable,
    };
  } else {
    if (field.fieldName === '__typename') {
      const typeName = typeNameFromGraphQLType(context, fieldType, null, false);
      return { ...property, typeName, isComposite: false, fieldType, isNullable: false };
    } else {
      const typeName = typeNameFromGraphQLType(context, fieldType, null, isNullable);
      return { ...property, typeName, isComposite: false, fieldType, isNullable };
    }
  }
}
Example #7
Source File: index.ts    From amplify-codegen with Apache License 2.0 4 votes vote down vote up
compileSelection(
    selectionNode: SelectionNode,
    parentType: GraphQLCompositeType,
    possibleTypes: GraphQLObjectType[],
    visitedFragments: Set<string>,
  ): Selection | null {
    switch (selectionNode.kind) {
      case Kind.FIELD: {
        const name = selectionNode.name.value;
        const alias = selectionNode.alias ? selectionNode.alias.value : undefined;

        const fieldDef = getFieldDef(this.schema, parentType, selectionNode);
        if (!fieldDef) {
          throw new GraphQLError(`Cannot query field "${name}" on type "${String(parentType)}"`, [selectionNode]);
        }

        const fieldType = fieldDef.type;
        const unmodifiedFieldType = getNamedType(fieldType);

        this.addTypeUsed(unmodifiedFieldType);

        const { description, isDeprecated, deprecationReason } = fieldDef;

        const responseKey = alias || name;

        const args =
          selectionNode.arguments && selectionNode.arguments.length > 0
            ? selectionNode.arguments.map(arg => {
                const name = arg.name.value;
                const argDef = fieldDef.args.find(argDef => argDef.name === arg.name.value);
                return {
                  name,
                  value: valueFromValueNode(arg.value),
                  type: (argDef && argDef.type) || undefined,
                };
              })
            : undefined;

        let field: Field = {
          kind: 'Field',
          responseKey,
          name,
          alias,
          args,
          type: fieldType,
          description: !isMetaFieldName(name) && description ? description : undefined,
          isDeprecated,
          deprecationReason: deprecationReason || undefined,
        };

        if (isCompositeType(unmodifiedFieldType)) {
          const selectionSetNode = selectionNode.selectionSet;
          if (!selectionSetNode) {
            throw new GraphQLError(`Composite field "${name}" on type "${String(parentType)}" requires selection set`, [selectionNode]);
          }

          field.selectionSet = this.compileSelectionSet(selectionNode.selectionSet as SelectionSetNode, unmodifiedFieldType);
        }
        return field;
      }
      case Kind.INLINE_FRAGMENT: {
        const typeNode = selectionNode.typeCondition;
        const type = typeNode ? (typeFromAST(this.schema, typeNode) as GraphQLCompositeType) : parentType;
        const possibleTypesForTypeCondition = this.possibleTypesForType(type).filter(type => possibleTypes.includes(type));
        return {
          kind: 'TypeCondition',
          type,
          selectionSet: this.compileSelectionSet(selectionNode.selectionSet, type, possibleTypesForTypeCondition),
        };
      }
      case Kind.FRAGMENT_SPREAD: {
        const fragmentName = selectionNode.name.value;
        if (visitedFragments.has(fragmentName)) return null;
        visitedFragments.add(fragmentName);

        const fragmentSpread: FragmentSpread = {
          kind: 'FragmentSpread',
          fragmentName,
          selectionSet: {
            possibleTypes,
            selections: [],
          },
        };
        this.unresolvedFragmentSpreads.push(fragmentSpread);
        return fragmentSpread;
      }
    }
  }
Example #8
Source File: codeGeneration.ts    From amplify-codegen with Apache License 2.0 4 votes vote down vote up
structDeclarationForVariant(
    {
      structName,
      adoptedProtocols = ['GraphQLSelectionSet'],
      variant,
      typeCase,
    }: {
      structName: string;
      adoptedProtocols?: string[];
      variant: Variant;
      typeCase?: TypeCase;
    },
    before?: Function,
    after?: Function
  ) {
    this.structDeclaration({ structName, adoptedProtocols }, () => {
      if (before) {
        before();
      }

      this.printNewlineIfNeeded();
      this.printOnNewline('public static let possibleTypes = [');
      this.print(join(variant.possibleTypes.map(type => `"${type.name}"`), ', '));
      this.print(']');

      this.printNewlineIfNeeded();
      this.printOnNewline('public static let selections: [GraphQLSelection] = ');
      if (typeCase) {
        this.typeCaseInitialization(typeCase);
      } else {
        this.selectionSetInitialization(variant);
      }

      this.printNewlineIfNeeded();

      this.propertyDeclaration({
        propertyName: 'snapshot',
        typeName: 'Snapshot',
      });

      this.printNewlineIfNeeded();
      this.printOnNewline('public init(snapshot: Snapshot)');
      this.withinBlock(() => {
        this.printOnNewline(`self.snapshot = snapshot`);
      });

      if (typeCase) {
        this.initializersForTypeCase(typeCase);
      } else {
        this.initializersForVariant(variant);
      }

      const fields = collectAndMergeFields(variant, this.context.options.mergeInFieldsFromFragmentSpreads).map(field =>
        this.helpers.propertyFromField(field as Field)
      );

      const fragmentSpreads = variant.fragmentSpreads.map(fragmentSpread => {
        const isConditional = variant.possibleTypes.some(type => !fragmentSpread.selectionSet.possibleTypes.includes(type));

        return this.helpers.propertyFromFragmentSpread(fragmentSpread, isConditional);
      });

      fields.forEach(this.propertyDeclarationForField, this);

      if (fragmentSpreads.length > 0) {
        this.printNewlineIfNeeded();
        this.printOnNewline(`public var fragments: Fragments`);
        this.withinBlock(() => {
          this.printOnNewline('get');
          this.withinBlock(() => {
            this.printOnNewline(`return Fragments(snapshot: snapshot)`);
          });
          this.printOnNewline('set');
          this.withinBlock(() => {
            this.printOnNewline(`snapshot += newValue.snapshot`);
          });
        });

        this.structDeclaration(
          {
            structName: 'Fragments',
          },
          () => {
            this.propertyDeclaration({
              propertyName: 'snapshot',
              typeName: 'Snapshot',
            });

            for (const fragmentSpread of fragmentSpreads) {
              const { propertyName, typeName, structName, isConditional } = fragmentSpread;

              this.printNewlineIfNeeded();
              this.printOnNewline(`public var ${escapeIdentifierIfNeeded(propertyName)}: ${typeName}`);
              this.withinBlock(() => {
                this.printOnNewline('get');
                this.withinBlock(() => {
                  if (isConditional) {
                    this.printOnNewline(`if !${structName}.possibleTypes.contains(snapshot["__typename"]! as! String) { return nil }`);
                  }
                  this.printOnNewline(`return ${structName}(snapshot: snapshot)`);
                });
                this.printOnNewline('set');
                this.withinBlock(() => {
                  if (isConditional) {
                    this.printOnNewline(`guard let newValue = newValue else { return }`);
                    this.printOnNewline(`snapshot += newValue.snapshot`);
                  } else {
                    this.printOnNewline(`snapshot += newValue.snapshot`);
                  }
                });
              });
            }
          }
        );
      }

      for (const field of fields) {
        if (isCompositeType(getNamedType(field.type)) && field.selectionSet) {
          this.structDeclarationForSelectionSet({
            structName: field.structName,
            selectionSet: field.selectionSet,
          });
        }
      }

      if (after) {
        after();
      }
    });
  }