graphql#isEnumType TypeScript Examples

The following examples show how to use graphql#isEnumType. 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
function getReturnTypeName(generator: CodeGenerator, op: LegacyOperation): String {
  const { operationName, operationType } = op;
  const { type } = op.fields[0];
  //List of scalar or enum type
  if (isListType(type)) {
    const { ofType } = type;
    if (isScalarType(ofType) || isEnumType(ofType)) {
      return `Array<${typeNameFromGraphQLType(generator.context, ofType)}>`;
    }
  }
  //Scalar and enum type
  if (isScalarType(type) || isEnumType(type)) {
    return typeNameFromGraphQLType(generator.context, type);
  }
  //Non scalar type
  else {
    let returnType = interfaceNameFromOperation({ operationName, operationType });
    if (op.operationType === 'subscription' && op.fields.length) {
      returnType = `Pick<__SubscriptionContainer, "${op.fields[0].responseName}">`;
    }
    if (isList(type)) {
      returnType = `Array<${returnType}>`;
    }
    return returnType;
  }
}
Example #2
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 #3
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 #4
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 #5
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 #6
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 #7
Source File: objectType.ts    From genql with MIT License 5 votes vote down vote up
objectType = (
    type: GraphQLObjectType | GraphQLInterfaceType,
    ctx: RenderContext,
    wrapper: 'Promise' | 'Observable',
) => {
    // console.log(Object.keys(type.getFields()))
    const fieldsMap: GraphQLFieldMap<any, any> = ctx.config?.sortProperties
        ? sortKeys(type.getFields())
        : type.getFields()

    const fieldStrings = Object.keys(fieldsMap).map((fieldName) => {
        const field = fieldsMap[fieldName]
        const resolvedType = getNamedType(field.type)
        // leaf type, obly has.get() method
        const stopChain =
            isListType(field.type) ||
            (isNonNullType(field.type) && isListType(field.type.ofType)) ||
            isUnionType(resolvedType)
        // non leaf type, has .get method
        const resolvable = !(
            isEnumType(resolvedType) || isScalarType(resolvedType)
        )
        const argsPresent = field.args.length > 0
        const argsOptional = !field.args.find((a) => isNonNullType(a.type))
        const argsString = toArgsString(field)

        const executeReturnType = renderTyping(field.type, true, false, false)
        const executeReturnTypeWithTypeMap = renderTyping(
            field.type,
            true,
            false,
            false,
            (x: string) => `FieldsSelection<${x}, R>`,
        )

        //     get: <R extends RepositoryRequest>(
        //         request: R,
        //         defaultValue?: Repository,
        //     ) => Promise<FieldsSelection<Repository, R>>
        // }

        const getFnType = `{get: <R extends ${requestTypeName(
            resolvedType,
        )}>(request: R, defaultValue?: ${executeReturnTypeWithTypeMap}) => ${wrapper}<${executeReturnTypeWithTypeMap}>}`
        const fieldType = resolvable
            ? stopChain
                ? getFnType
                : `${chainTypeName(resolvedType, wrapper)} & ${getFnType}`
            : `{get: (request?: boolean|number, defaultValue?: ${executeReturnType}) => ${wrapper}<${executeReturnType}>}`

        const result: string[] = []

        if (argsPresent) {
            result.push(
                `((args${
                    argsOptional ? '?' : ''
                }: ${argsString}) => ${fieldType})`,
            )
        }

        if (!argsPresent || argsOptional) {
            result.push(`(${fieldType})`)
        }

        return `${fieldComment(field)}${field.name}: ${result.join('&')}`
    })

    ctx.addImport(RUNTIME_LIB_NAME, false, 'FieldsSelection', true, true)

    if (wrapper === 'Observable') {
        ctx.addImport(RUNTIME_LIB_NAME, false, 'Observable', true, true)
    }

    ctx.addCodeBlock(
        `${typeComment(type)}export interface ${chainTypeName(
            type,
            wrapper,
        )}{\n    ${fieldStrings.join(',\n    ')}\n}`,
    )
}
Example #8
Source File: renderClient.ts    From genql with MIT License 5 votes vote down vote up
export function renderEnumsMaps(
    schema: GraphQLSchema,
    moduleType: 'esm' | 'cjs' | 'type',
) {
    let typeMap = schema.getTypeMap()

    const enums: GraphQLEnumType[] = []
    for (const name in typeMap) {
        if (excludedTypes.includes(name)) continue

        const type = typeMap[name]

        if (isEnumType(type)) {
            enums.push(type)
        }
    }
    if (enums.length === 0) return ''
    const declaration = (() => {
        if (moduleType === 'esm') {
            return 'export const '
        } else if (moduleType === 'cjs') {
            return 'module.exports.'
        } else if (moduleType === 'type') {
            return 'export declare const '
        }
        return ''
    })()
    return enums
        .map(
            (type) =>
                `${declaration}${camelCase('enum' + type.name)}${moduleType === 'type' ? ': ' : ' = '}{\n` +
                type
                    .getValues()
                    .map((v) => {
                        if (!v?.name) {
                            return ''
                        }
                        return `  ${moduleType === 'type' ? 'readonly ' : ''}${v.name}: '${v.name}'`
                    })
                    .join(',\n') +
                `\n}\n`,
        )
        .join('\n')
}
Example #9
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 #10
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),
    )
    


}