graphql#isInterfaceType TypeScript Examples

The following examples show how to use graphql#isInterfaceType. 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: index.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
addTypeUsed(type: GraphQLType) {
    if (this.typesUsedSet.has(type)) return;

    if (
      isEnumType(type) ||
      isUnionType(type) ||
      isInputObjectType(type) ||
      isInterfaceType(type) ||
      isObjectType(type) ||
      (isScalarType(type) && !isSpecifiedScalarType(type))
    ) {
      this.typesUsedSet.add(type);
    }
    if (isInterfaceType(type) || isUnionType(type)) {
      for (const concreteType of this.schema.getPossibleTypes(type)) {
        this.addTypeUsed(getNamedType(concreteType));
      }
    }
    if (isInputObjectType(type)) {
      for (const field of Object.values(type.getFields())) {
        this.addTypeUsed(getNamedType(field.type));
      }
    }
    if (isObjectType(type)) {
      for (const fieldType of type.getInterfaces()) {
        this.addTypeUsed(getNamedType(fieldType));
      }
      for (const field of Object.values(type.getFields())) {
        this.addTypeUsed(getNamedType(field.type));
      }
    }
  }
Example #2
Source File: serializeToJSON.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
function serializeType(type: GraphQLType) {
  if (isEnumType(type)) {
    return serializeEnumType(type);
  } else if (isUnionType(type)) {
    return serializeUnionType(type);
  } else if (isInputObjectType(type)) {
    return serializeInputObjectType(type);
  } else if (isObjectType(type)) {
    return serializeObjectType(type);
  } else if (isInterfaceType(type)) {
    return serializeInterfaceType(type);
  } else if (isScalarType(type)) {
    return serializeScalarType(type);
  } else {
    throw new Error(`Unexpected GraphQL type: ${type}`);
  }
}
Example #3
Source File: codeGeneration.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
export function typeDeclarationForGraphQLType(generator: CodeGenerator, type: GraphQLType) {
  if (isEnumType(type)) {
    enumerationDeclaration(generator, type);
  } else if (isUnionType(type)) {
    unionDeclaration(generator, type);
  } else if (isInputObjectType(type)) {
    structDeclarationForInputObjectType(generator, type);
  } else if (isObjectType(type)) {
    structDeclarationForObjectType(generator, type);
  } else if (isInterfaceType(type)) {
    structDeclarationForInterfaceType(generator, type);
  }
}
Example #4
Source File: codeGeneration.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
/**
 * This exists only to properly generate types for union/interface typed fields that
 * do not have inline fragments. This currently can happen and the IR does give us
 * a set of fields per type condition unless fragments are used within the selection set.
 */
function getPossibleTypeNames(generator: CodeGenerator<LegacyCompilerContext>, property: Property) {
  const type = getNamedType(property.fieldType || property.type!);

  if (isUnionType(type) || isInterfaceType(type)) {
    return generator.context.schema.getPossibleTypes(type).map(type => type.name);
  }

  return [];
}
Example #5
Source File: renderChainTypes.ts    From genql with MIT License 6 votes vote down vote up
renderChainTypes = (schema: GraphQLSchema, ctx: RenderContext) => {
  const typeMap = ctx.config?.sortProperties
    ? sortKeys(schema.getTypeMap())
    : schema.getTypeMap()

  for (const name in typeMap) {
    if (excludedTypes.includes(name)) continue

    const type = typeMap[name]

    // TODO handle unions
    if (isObjectType(type) || isInterfaceType(type)) {
      objectType(type, ctx, 'Promise')
      objectType(type, ctx, 'Observable')
    }
  }
}
Example #6
Source File: renderRequestTypes.ts    From genql with MIT License 6 votes vote down vote up
renderRequestTypes = (
    schema: GraphQLSchema,
    ctx: RenderContext,
) => {
    let typeMap = schema.getTypeMap()

    if (ctx.config?.sortProperties) {
        typeMap = sortKeys(typeMap)
    }

    for (const name in typeMap) {
        if (excludedTypes.includes(name)) continue

        const type = typeMap[name]

        if (isObjectType(type) || isInterfaceType(type)) objectType(type, ctx)
        if (isInputObjectType(type)) inputObjectType(type, ctx)
        if (isUnionType(type)) unionType(type, ctx)
    }

    const aliases = [
        { type: schema.getQueryType(), name: 'QueryRequest' },
        { type: schema.getMutationType(), name: 'MutationRequest' },
        { type: schema.getSubscriptionType(), name: 'SubscriptionRequest' },
    ]
        .map(renderAlias)
        .filter(Boolean)
        .join('\n')

    ctx.addCodeBlock(aliases)
}
Example #7
Source File: renderResponseTypes.ts    From genql with MIT License 6 votes vote down vote up
renderResponseTypes = (
    schema: GraphQLSchema,
    ctx: RenderContext,
) => {
    let typeMap = schema.getTypeMap()
    if (ctx.config?.sortProperties) {
        typeMap = sortKeys(typeMap)
    }
    ctx.addCodeBlock(
        renderScalarTypes(
            ctx,
            Object.values(typeMap).filter((type): type is GraphQLScalarType =>
                isScalarType(type),
            ),
        ),
    )
    for (const name in typeMap) {
        if (excludedTypes.includes(name)) continue

        const type = typeMap[name]

        if (isEnumType(type)) enumType(type, ctx)
        if (isUnionType(type)) unionType(type, ctx)
        if (isObjectType(type)) objectType(type, ctx)
        if (isInterfaceType(type)) interfaceType(type, ctx)
    }

    const aliases = [
        { type: schema.getQueryType(), name: 'Query' },
        { type: schema.getMutationType(), name: 'Mutation' },
        { type: schema.getSubscriptionType(), name: 'Subscription' },
    ]
        .map(renderAlias)
        .filter(Boolean)
        .join('\n')
    ctx.addCodeBlock(aliases)
}
Example #8
Source File: renderTypeGuards.ts    From genql with MIT License 6 votes vote down vote up
renderTypeGuards = (
    schema: GraphQLSchema,
    ctx: RenderContext,
    isJs: 'ts' | 'esm' | 'cjs' = 'ts',
) => {
    const typeMap = schema.getTypeMap()
    for (const name in typeMap) {
        if (excludedTypes.includes(name)) continue

        const type = typeMap[name]

        if (isUnionType(type)) {
            const types = type.getTypes().map((t) => t.name)
            ctx.addCodeBlock(renderTypeGuard(type.name, types, isJs))
        } else if (isInterfaceType(type)) {
            const types = schema.getPossibleTypes(type).map((t) => t.name)
            ctx.addCodeBlock(renderTypeGuard(type.name, types, isJs))
        } else if (isObjectType(type)) {
            ctx.addCodeBlock(renderTypeGuard(type.name, [type.name], isJs))
        }
    }
}
Example #9
Source File: no-unreachable-types.ts    From graphql-eslint with MIT License 5 votes vote down vote up
function getReachableTypes(schema: GraphQLSchema): ReachableTypes {
  // We don't want cache reachableTypes on test environment
  // Otherwise reachableTypes will be same for all tests
  if (process.env.NODE_ENV !== 'test' && reachableTypesCache) {
    return reachableTypesCache;
  }
  const reachableTypes: ReachableTypes = new Set();

  const collect = (node: ASTNode): false | void => {
    const typeName = getTypeName(node);
    if (reachableTypes.has(typeName)) {
      return;
    }
    reachableTypes.add(typeName);
    const type = schema.getType(typeName) || schema.getDirective(typeName);

    if (isInterfaceType(type)) {
      const { objects, interfaces } = schema.getImplementations(type);
      for (const { astNode } of [...objects, ...interfaces]) {
        visit(astNode, visitor);
      }
    } else if (type.astNode) {
      // astNode can be undefined for ID, String, Boolean
      visit(type.astNode, visitor);
    }
  };

  const visitor: ASTVisitor = {
    InterfaceTypeDefinition: collect,
    ObjectTypeDefinition: collect,
    InputValueDefinition: collect,
    UnionTypeDefinition: collect,
    FieldDefinition: collect,
    Directive: collect,
    NamedType: collect,
  };

  for (const type of [
    schema, // visiting SchemaDefinition node
    schema.getQueryType(),
    schema.getMutationType(),
    schema.getSubscriptionType(),
  ]) {
    // if schema don't have Query type, schema.astNode will be undefined
    if (type?.astNode) {
      visit(type.astNode, visitor);
    }
  }
  reachableTypesCache = reachableTypes;
  return reachableTypesCache;
}
Example #10
Source File: getFields.ts    From amplify-codegen with Apache License 2.0 5 votes vote down vote up
export default function getFields(
  field: GraphQLField<any, any>,
  schema: GraphQLSchema,
  depth: number = 2,
  options: GQLDocsGenOptions
): GQLTemplateField {
  const fieldType: GQLConcreteType = getType(field.type);
  const renderS3FieldFragment = options.useExternalFragmentForS3Object && isS3Object(fieldType);
  const subFields = !renderS3FieldFragment && (isObjectType(fieldType) || isInterfaceType(fieldType)) ? fieldType.getFields() : [];

  const subFragments: any = isInterfaceType(fieldType) || isUnionType(fieldType) ? schema.getPossibleTypes(fieldType) : {};

  if (depth < 1 && !(isScalarType(fieldType) || isEnumType(fieldType))) {
    return;
  }

  const fields: Array<GQLTemplateField> = Object.keys(subFields)
    .map(fieldName => {
      const subField = subFields[fieldName];
      return getFields(subField, schema, adjustDepth(subField, depth), options);
    })
    .filter(f => f);
  const fragments: Array<GQLTemplateFragment> = Object.keys(subFragments)
    .map(fragment => getFragment(subFragments[fragment], schema, depth, fields, null, false, options))
    .filter(f => f);

  // Special treatment for S3 input
  // Swift SDK needs S3 Object to have fragment
  if (renderS3FieldFragment) {
    fragments.push(getFragment(fieldType as GraphQLObjectType, schema, depth, [], 'S3Object', true, options));
  }

  // if the current field is an object and none of the subfields are included, don't include the field itself
  if (!(isScalarType(fieldType) || isEnumType(fieldType)) && fields.length === 0 && fragments.length === 0 && !renderS3FieldFragment) {
    return;
  }

  return {
    name: field.name,
    fields,
    fragments,
    hasBody: !!(fields.length || fragments.length),
  };
}
Example #11
Source File: objectType.ts    From genql with MIT License 5 votes vote down vote up
objectType = (
    type: GraphQLObjectType | GraphQLInterfaceType,
    ctx: RenderContext,
) => {
    let fields = type.getFields()

    if (ctx.config?.sortProperties) {
        fields = sortKeys(fields)
    }

    let fieldStrings = Object.keys(fields).map((fieldName) => {
        const field = fields[fieldName]

        const types: string[] = []
        const resolvedType = getNamedType(field.type)
        const resolvable = !(
            isEnumType(resolvedType) || isScalarType(resolvedType)
        )
        const argsPresent = field.args.length > 0
        const argsString = toArgsString(field)
        const argsOptional = !argsString.match(/[^?]:/)

        if (argsPresent) {
            if (resolvable) {
                types.push(`[${argsString},${requestTypeName(resolvedType)}]`)
            } else {
                types.push(`[${argsString}]`)
            }
        }

        if (!argsPresent || argsOptional) {
            if (resolvable) {
                types.push(`${requestTypeName(resolvedType)}`)
            } else {
                types.push('boolean | number')
            }
        }

        return `${fieldComment(field)}${field.name}?: ${types.join(' | ')}`
    })

    if (isInterfaceType(type) && ctx.schema) {
        let interfaceProperties = ctx.schema
            .getPossibleTypes(type)
            .map((t) => `on_${t.name}?: ${requestTypeName(t)}`)
        if (ctx.config?.sortProperties) {
            interfaceProperties = interfaceProperties.sort()
        }
        fieldStrings = fieldStrings.concat(interfaceProperties)
    }

    fieldStrings.push('__typename?: boolean | number')
    fieldStrings.push('__scalar?: boolean | number')

    // add indentation
    fieldStrings = fieldStrings.map((x) =>
        x
            .split('\n')
            .filter(Boolean)
            .map((l) => INDENTATION + l)
            .join('\n'),
    )

    ctx.addCodeBlock(
        `${typeComment(type)}export interface ${requestTypeName(
            type,
        )}{\n${fieldStrings.join('\n')}\n}`,
    )
}
Example #12
Source File: objectType.ts    From genql with MIT License 5 votes vote down vote up
objectType = (
    type: GraphQLObjectType | GraphQLInterfaceType | GraphQLInputObjectType,
    ctx: RenderContext,
) => {
    const typeObj: FieldMap<string> = Object.keys(type.getFields()).reduce<
        FieldMap<string>
    >((r, f) => {
        const field = type.getFields()[f]
        const namedType = getNamedType(field.type)
        const fieldObj: Field<string> = { type: namedType.name }
        r[f] = fieldObj

        const args: GraphQLArgument[] =
            (<GraphQLField<any, any>>field).args || []

        if (args.length > 0) {
            fieldObj.args = args.reduce<ArgMap<string>>((r, a) => {
                const concreteType = a.type.toString()
                const typename = getNamedType(a.type).name
                r[a.name] = [typename]
                if (typename !== concreteType) {
                    r[a.name]?.push(concreteType)
                }
                return r
            }, {})
        }

        return r
    }, {})

    if (isInterfaceType(type) && ctx.schema) {
        ctx.schema.getPossibleTypes(type).map((t) => {
            if (!isEmpty(typeObj)) {
                typeObj[`on_${t.name}`] = { type: t.name }
            }
        })
    }

    if (!isEmpty(typeObj)) {
        typeObj.__typename = { type: 'String' }
    }

    // const scalar = Object.keys(type.getFields())
    //   .map(f => type.getFields()[f])
    //   .filter(f => isScalarType(getNamedType(f.type)) || isEnumType(getNamedType(f.type)))
    //   .map(f => f.name)

    // if (scalar.length > 0) typeObj.scalar = scalar

    return typeObj
}
Example #13
Source File: renderTypeMap.ts    From genql with MIT License 5 votes vote down vote up
renderTypeMap = (schema: GraphQLSchema, ctx: RenderContext) => {
    // remove fields key,
    // remove the Type.type and Type.args, replace with [type, args]
    // reverse args.{name}
    // Args type is deduced and added only when the concrete type is different from type name, remove the scalar field and replace with a top level scalars array field.
    const result: TypeMap<string> = {
        scalars: [],
        types: {},
    }

    Object.keys(schema.getTypeMap())
        .filter((t) => !excludedTypes.includes(t))
        .map((t) => schema.getTypeMap()[t])
        .map((t) => {
            if (isObjectType(t) || isInterfaceType(t) || isInputObjectType(t))
                result.types[t.name] = objectType(t, ctx)
            else if (isUnionType(t)) result.types[t.name] = unionType(t, ctx)
            else if (isScalarType(t) || isEnumType(t)) {
                result.scalars.push(t.name)
                result.types[t.name] = {}
            }
        })

    // change names of query, mutation on schemas that chose different names (hasura)
    const q = schema.getQueryType()
    if (q?.name && q?.name !== 'Query') {
        delete result.types[q.name]
        result.types.Query = objectType(q, ctx)
        // result.Query.name = 'Query'
    }

    const m = schema.getMutationType()
    if (m?.name && m.name !== 'Mutation') {
        delete result.types[m.name]
        result.types.Mutation = objectType(m, ctx)
        // result.Mutation.name = 'Mutation'
    }

    const s = schema.getSubscriptionType()
    if (s?.name && s.name !== 'Subscription') {
        delete result.types[s.name]
        result.types.Subscription = objectType(s, ctx)
        // result.Subscription.name = 'Subscription'
    }

    ctx.addCodeBlock(
        JSON.stringify(replaceTypeNamesWithIndexes(result), null, 4),
    )
    


}
Example #14
Source File: resolve-additional-resolvers.ts    From graphql-mesh with MIT License 4 votes vote down vote up
function generateSelectionSetFactory(
  schema: GraphQLSchema,
  additionalResolver: YamlConfig.AdditionalStitchingBatchResolverObject | YamlConfig.AdditionalStitchingResolverObject
) {
  if (additionalResolver.sourceSelectionSet) {
    return () => parseSelectionSet(additionalResolver.sourceSelectionSet);
    // If result path provided without a selectionSet
  } else if (additionalResolver.result) {
    const resultPath = toPath(additionalResolver.result);
    let abstractResultTypeName: string;

    const sourceType = schema.getType(additionalResolver.sourceTypeName) as GraphQLObjectType;
    const sourceTypeFields = sourceType.getFields();
    const sourceField = sourceTypeFields[additionalResolver.sourceFieldName];
    const resultFieldType = getTypeByPath(sourceField.type, resultPath);

    if (isAbstractType(resultFieldType)) {
      if (additionalResolver.resultType) {
        abstractResultTypeName = additionalResolver.resultType;
      } else {
        const targetType = schema.getType(additionalResolver.targetTypeName) as GraphQLObjectType;
        const targetTypeFields = targetType.getFields();
        const targetField = targetTypeFields[additionalResolver.targetFieldName];
        const targetFieldType = getNamedType(targetField.type);
        abstractResultTypeName = targetFieldType?.name;
      }
      if (abstractResultTypeName !== resultFieldType.name) {
        const abstractResultType = schema.getType(abstractResultTypeName);
        if (
          (isInterfaceType(abstractResultType) || isObjectType(abstractResultType)) &&
          !schema.isSubType(resultFieldType, abstractResultType)
        ) {
          throw new Error(
            `${additionalResolver.sourceTypeName}.${additionalResolver.sourceFieldName}.${resultPath.join(
              '.'
            )} doesn't implement ${abstractResultTypeName}.}`
          );
        }
      }
    }

    return (subtree: SelectionSetNode) => {
      let finalSelectionSet = subtree;
      let isLastResult = true;
      const resultPathReversed = [...resultPath].reverse();
      for (const pathElem of resultPathReversed) {
        // Ensure the path elem is not array index
        if (Number.isNaN(parseInt(pathElem))) {
          if (isLastResult && abstractResultTypeName && abstractResultTypeName !== resultFieldType.name) {
            finalSelectionSet = {
              kind: Kind.SELECTION_SET,
              selections: [
                {
                  kind: Kind.INLINE_FRAGMENT,
                  typeCondition: {
                    kind: Kind.NAMED_TYPE,
                    name: {
                      kind: Kind.NAME,
                      value: abstractResultTypeName,
                    },
                  },
                  selectionSet: finalSelectionSet,
                },
              ],
            };
          }
          finalSelectionSet = {
            kind: Kind.SELECTION_SET,
            selections: [
              {
                // we create a wrapping AST Field
                kind: Kind.FIELD,
                name: {
                  kind: Kind.NAME,
                  value: pathElem,
                },
                // Inside the field selection
                selectionSet: finalSelectionSet,
              },
            ],
          };
          isLastResult = false;
        }
      }
      return finalSelectionSet;
    };
  }
  return undefined;
}