graphql#GraphQLEnumType TypeScript Examples

The following examples show how to use graphql#GraphQLEnumType. 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: utils.ts    From tql with MIT License 7 votes vote down vote up
printType = (type: GraphQLNamedType) => {
  if (type instanceof GraphQLScalarType) {
    return `${type.name}: ${toPrimitive(type)}`;
  } else if (type instanceof GraphQLEnumType) {
    return `${type.name}: ${type.name}`;
  } else {
    return `${type.name}: I${type.name}`;
  }
}
Example #2
Source File: schema_builder.ts    From graphql-mesh with MIT License 6 votes vote down vote up
/**
 * Creates an enum type or returns an existing one, and stores it in data
 */
function createOrReuseEnum<TSource, TContext, TArgs>({
  def,
  logger,
}: CreateOrReuseSimpleTypeParams<TSource, TContext, TArgs>): GraphQLEnumType {
  const translationLogger = logger.child('translation');
  /**
   * Try to reuse existing enum type
   *
   * Enum types do not have an input variant so only check def.ot
   */
  if (def.graphQLType && typeof def.graphQLType !== 'undefined') {
    translationLogger.debug(`Reuse GraphQLEnumType '${def.graphQLTypeName}'`);
    return def.graphQLType as GraphQLEnumType;
  } else {
    translationLogger.debug(`Create GraphQLEnumType '${def.graphQLTypeName}'`);

    const values = {};
    def.schema.enum.forEach(e => {
      // Force enum values to string and value should be in ALL_CAPS
      values[Oas3Tools.sanitize(e.toString(), Oas3Tools.CaseStyle.ALL_CAPS)] = {
        value: e,
      };
    });

    // Store newly created Enum Object Type
    def.graphQLType = new GraphQLEnumType({
      name: def.graphQLTypeName,
      values,
    });

    return def.graphQLType;
  }
}
Example #3
Source File: types.ts    From tql with MIT License 6 votes vote down vote up
printField = (field: GraphQLField<any, any, any>): string => {
  const { args } = field;

  const isList = listType(field.type);
  const isNonNull = field.type instanceof GraphQLNonNull;
  const type = outputType(field.type);

  const printVariables = () => {
    return args.length > 0
      ? `(variables: { ${args.map(printVariable).join(", ")} })`
      : "";
  };

  if (type instanceof GraphQLScalarType) {
    return (
      `${args.length > 0 ? "" : "readonly"} ${field.name}${printVariables()}: ${
        isList ? `ReadonlyArray<${toPrimitive(type)}>` : `${toPrimitive(type)}`
      }` + (isNonNull ? "" : " | null")
    );
  } else if (type instanceof GraphQLEnumType) {
    return (
      `${args.length > 0 ? "" : "readonly"} ${field.name}${printVariables()}: ${
        isList ? `ReadonlyArray<${type.name}>` : `${type.name}`
      }` + (isNonNull ? "" : " | null")
    );
  } else if (
    type instanceof GraphQLInterfaceType ||
    type instanceof GraphQLUnionType ||
    type instanceof GraphQLObjectType
  ) {
    return (
      `${args.length > 0 ? "" : "readonly"} ${field.name}${printVariables()}: ${
        isList ? `ReadonlyArray<I${type.name}>` : `I${type.name}`
      }` + (isNonNull ? "" : " | null")
    );
  } else {
    throw new Error("Unable to print field.");
  }
}
Example #4
Source File: selectors.ts    From tql with MIT License 6 votes vote down vote up
printArgument = (arg: GraphQLArgument): string => {
  const type = inputType(arg.type);
  const typename =
    type instanceof GraphQLScalarType
      ? toPrimitive(type)
      : type instanceof GraphQLEnumType
      ? type.toString()
      : "I" + type.toString();

  return `Argument<"${arg.name}", V['${arg.name}']>`;
}
Example #5
Source File: printers.ts    From tql with MIT License 6 votes vote down vote up
printInputType = (type: GraphQLInputType): string => {
  const isList = listType(type);
  const base = inputType(type);

  return (
    (() => {
      if (base instanceof GraphQLScalarType) {
        return toPrimitive(base);
      } else if (base instanceof GraphQLEnumType) {
        return base.name;
      } else if (base instanceof GraphQLInputObjectType) {
        return "I" + base.name;
      } else {
        throw new Error("Unable to render inputType.");
      }
    })() + (isList ? "[]" : "")
  );
}
Example #6
Source File: schema.ts    From squid with GNU General Public License v3.0 6 votes vote down vote up
function addEnum(model: Model, type: GraphQLEnumType): void {
    if (model[type.name]) return
    let values: Record<string, {}> = {}

    model[type.name] = {
        kind: 'enum',
        values,
        description: type.description || undefined
    }

    type.getValues().forEach(item => {
        values[item.name] = {}
    })
}
Example #7
Source File: buildLocaleInputType.ts    From payload with MIT License 6 votes vote down vote up
buildLocaleInputType = (localization: SanitizedConfig['localization']): GraphQLEnumType => new GraphQLEnumType({
  name: 'LocaleInputType',
  values: localization.locales.reduce((values, locale) => ({
    ...values,
    [locale]: {
      value: locale,
    },
  }), {}),
})
Example #8
Source File: buildFallbackLocaleInputType.ts    From payload with MIT License 6 votes vote down vote up
buildFallbackLocaleInputType = (localization: SanitizedConfig['localization']): GraphQLEnumType => new GraphQLEnumType({
  name: 'FallbackLocaleInputType',
  values: [...localization.locales, 'none'].reduce((values, locale) => ({
    ...values,
    [locale]: {
      value: locale,
    },
  }), {}),
})
Example #9
Source File: visitor.ts    From proto2graphql with MIT License 6 votes vote down vote up
function visitEnum(enm: protobuf.Enum, context: Context) {
  const enumType = new GraphQLEnumType({
    name: fullTypeName(enm),
    values: Object.assign(
      {},
      ...Object.keys(enm.values).map(key => ({
        [key]: {
          value: enm.values[key].valueOf()
        }
      }))
    )
  });
  setType(enumType, context);
  return enumType;
}
Example #10
Source File: Writer.ts    From graphql-ts-client with MIT License 6 votes vote down vote up
protected importType(type: GraphQLType) {
        if (this.imported) {
            throw new Error("Writer's importing has been terminated");
        }
        if (type instanceof GraphQLNonNull) {
            this.importType(type.ofType);
        } else if (type instanceof GraphQLList) {
            this.importType(type.ofType);
        } else if (type instanceof GraphQLInputObjectType) {
            this.importedTypes.add(type);
        } else if (type instanceof GraphQLEnumType) {
            this.importedTypes.add(type);
        } else if (type instanceof GraphQLScalarType && this.config.scalarTypeMap !== undefined) {
            const mappedType = this.config.scalarTypeMap[type.name];
            if (typeof mappedType == 'object') {
                const importSource = mappedType.importSource;
                let set = this.importedScalarTypes.get(importSource);
                if (set === undefined) {
                    set = new Set<string>();
                    this.importedScalarTypes.set(importSource, set);
                }
                set.add(mappedType.typeName);
            };
        }
    }
Example #11
Source File: Generator.ts    From graphql-ts-client with MIT License 6 votes vote down vote up
private async generateEnumTypes(enumTypes: GraphQLEnumType[]) {
        const dir = join(this.config.targetDir, "enums");
        const promises = enumTypes.map(async type => {
            const stream = createStreamAndLog(
                join(dir, `${type.name}.ts`)
            );
            new EnumWriter(type, stream, this.config).write();
            await stream.end();
        });
        await Promise.all([
            ...promises,
            this.writeSimpleIndex(dir, enumTypes)
        ]);
    }
Example #12
Source File: codeGeneration.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
function enumerationDeclaration(generator: CodeGenerator, type: GraphQLEnumType) {
  const { name, description } = type;
  const values = type.getValues();

  generator.printNewlineIfNeeded();
  if (description) {
    description.split('\n').forEach(line => {
      generator.printOnNewline(`// ${line.trim()}`);
    });
  }
  generator.printOnNewline(`export enum ${name} {`);
  values.forEach(value => {
    if (!value.description || value.description.indexOf('\n') === -1) {
      generator.printOnNewline(`  ${value.value} = "${value.value}",${wrap(' // ', value.description || '')}`);
    } else {
      if (value.description) {
        value.description.split('\n').forEach(line => {
          generator.printOnNewline(`  // ${line.trim()}`);
        });
      }
      generator.printOnNewline(`  ${value.value} = "${value.value}",`);
    }
  });
  generator.printOnNewline(`}`);
  generator.printNewline();
}
Example #13
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 #14
Source File: serializeToJSON.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
function serializeEnumType(type: GraphQLEnumType) {
  const { name, description } = type;
  const values = type.getValues();

  return {
    kind: 'EnumType',
    name,
    description,
    values: values.map(value => ({
      name: value.name,
      description: value.description,
      isDeprecated: value.isDeprecated,
      deprecationReason: value.deprecationReason,
    })),
  };
}
Example #15
Source File: codeGeneration.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
function printEnumsAndInputObjects(generator: FlowAPIGenerator, context: CompilerContext) {
  generator.printer.enqueue(stripIndent`
    //==============================================================
    // START Enums and Input Objects
    // All enums and input objects are included in every output file
    // for now, but this will be changed soon.
    // TODO: Link to issue to fix this.
    //==============================================================
  `);

  context.typesUsed
    .filter(type => type instanceof GraphQLEnumType)
    .forEach(enumType => {
      generator.typeAliasForEnumType(enumType as GraphQLEnumType);
    });

  context.typesUsed
    .filter(type => type instanceof GraphQLInputObjectType)
    .forEach(inputObjectType => {
      generator.typeAliasForInputObjectType(inputObjectType as GraphQLInputObjectType);
    });

  generator.printer.enqueue(stripIndent`
    //==============================================================
    // END Enums and Input Objects
    //==============================================================
  `);
}
Example #16
Source File: language.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
public enumerationDeclaration(type: GraphQLEnumType) {
    const { name, description } = type;
    const unionValues = type.getValues().map(({ value }) => {
      const type = t.stringLiteralTypeAnnotation();
      type.value = value;

      return type;
    });

    const typeAlias = t.exportNamedDeclaration(t.typeAlias(t.identifier(name), undefined, t.unionTypeAnnotation(unionValues)), []);

    typeAlias.leadingComments = [
      {
        type: 'CommentLine',
        value: ` ${description}`,
      } as t.CommentLine,
    ];

    return typeAlias;
  }
Example #17
Source File: schema.ts    From Deep-Lynx with MIT License 5 votes vote down vote up
// each key in the relationship should be included on the input object as a field to be filtered on
    inputFieldsForRelationship(relationship: MetatypeRelationship): {[key: string]: any} {
        const fields: {[key: string]: any} = {};

        relationship.keys?.forEach((relationshipKey) => {
            const propertyName = stringToValidPropertyName(relationshipKey.property_name);

            switch (relationshipKey.data_type) {
                // because we have no specification on our internal number type, we
                // must set this as a float for now
                case 'number': {
                    fields[propertyName] = {
                        type: GraphQLFloat,
                    };
                    break;
                }

                case 'boolean': {
                    fields[propertyName] = {
                        type: GraphQLBoolean,
                    };
                    break;
                }

                case 'string' || 'date' || 'file': {
                    fields[propertyName] = {
                        type: GraphQLString,
                    };
                    break;
                }

                case 'list': {
                    fields[propertyName] = {
                        type: new GraphQLList(GraphQLJSON),
                    };
                    break;
                }

                case 'enumeration': {
                    const enumMap: {[key: string]: GraphQLEnumValueConfig} = {};

                    if (relationshipKey.options) {
                        relationshipKey.options.forEach((option) => {
                            enumMap[option] = {
                                value: option,
                            };
                        });
                    }

                    fields[propertyName] = {
                        type: new GraphQLEnumType({
                            name: stringToValidPropertyName(`${relationship.name}_${relationshipKey.name}_Enum_TypeB`),
                            values: enumMap,
                        }),
                    };
                    break;
                }

                default: {
                    fields[propertyName] = {
                        type: GraphQLString,
                    };
                }
            }
        });
        return fields;
    }
Example #18
Source File: schema.ts    From squid with GNU General Public License v3.0 5 votes vote down vote up
function canBeIndexed(f: GraphQLField<any, any>): boolean {
    let type = asNonNull(f)
    if (type instanceof GraphQLScalarType || type instanceof GraphQLEnumType) return true
    return isEntityType(type) && !f.astNode?.directives?.some(d => d.name.value == 'derivedFrom')
}
Example #19
Source File: codeGeneration.ts    From amplify-codegen with Apache License 2.0 5 votes vote down vote up
public typeAliasForEnumType(enumType: GraphQLEnumType) {
    this.printer.enqueue(this.enumerationDeclaration(enumType));
  }
Example #20
Source File: render.ts    From tql with MIT License 5 votes vote down vote up
render = (sdl: string): string => {
  const ast = parse(sdl, { noLocation: true });
  const schema = buildSchema(sdl);

  const transforms = [
    typeTransform(ast, schema),
    selectorInterfaceTransform(ast, schema),
  ];

  // additive transforms
  const results = transforms.map(
    (vistor) => visit(ast, vistor)
  ) as unknown as Array<{ readonly definitions: Code[] }> ;

  const types = Object.values(schema.getTypeMap()).filter(
    (type) => !type.name.startsWith("__")
  );

  const enumValues = new Set(
    Object.values(schema.getTypeMap())
      .filter((type) => type instanceof GraphQLEnumType)
      .flatMap((type) =>
        (type as GraphQLEnumType).getValues().map((value) => value.value)
      )
  );

  const ENUMS = `
    Object.freeze({
      ${Array.from(enumValues)
        .map((value) => `${value}: true`)
        .join(",\n")}
    } as const)
  `;

  const typeMap = `
    export interface ISchema {
      ${types.map(printType).join("\n")}
    }
  `;

  const source =
    `
    import { buildASTSchema, Kind, OperationTypeNode } from 'graphql'

    import {
      TypeConditionError,
      NamedType,
      Field,
      InlineFragment,
      Argument,
      Variable,
      Selection,
      SelectionSet,
      SelectionBuilder,
      namedType,
      field,
      inlineFragment,
      argument,
      selectionSet
     } from '@timkendall/tql'

     export type { Result, SelectionResult, Variables } from '@timkendall/tql'
     export { $ } from '@timkendall/tql'

     ` +
    `
    export const SCHEMA = buildASTSchema(${stringifyAST(ast)})

    export const ENUMS = ${ENUMS}

    ${typeMap}
  ` +
    results
      .flatMap((result) =>
        result.definitions.map((code) => code.toCodeString())
      )
      .join("\n");

  return prettier.format(source, { parser: "typescript" });
}
Example #21
Source File: scalarType.ts    From genql with MIT License 5 votes vote down vote up
scalarType = (
    type: GraphQLScalarType | GraphQLEnumType,
    _: RenderContext,
): Type<string> => ({})
Example #22
Source File: enumType.ts    From genql with MIT License 5 votes vote down vote up
enumType = (type: GraphQLEnumType, ctx: RenderContext) => {
  const values = type.getValues().map(v => `'${v.name}'`)
  ctx.addCodeBlock(`${typeComment(type)}export type ${type.name} = ${values.join(' | ')}`)
}
Example #23
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 #24
Source File: selectors.ts    From tql with MIT License 5 votes vote down vote up
printMethod = (field: GraphQLField<any, any, any>): string => {
  const { name, args } = field;

  const type = outputType(field.type);

  const comments = [
    field.description && `@description ${field.description}`,
    field.deprecationReason && `@deprecated ${field.deprecationReason}`,
  ].filter(Boolean);

  const jsDocComment =
    comments.length > 0
      ? `
  /**
   ${comments.map((comment) => "* " + comment).join("\n")}
    */
  `
      : "";

  if (type instanceof GraphQLScalarType || type instanceof GraphQLEnumType) {
    // @todo render arguments correctly
    return args.length > 0
      ? jsDocComment.concat(
          `${name}: (variables) => field("${name}", Object.entries(variables).map(([k, v]) => argument(k, v)) as any),`
        )
      : jsDocComment.concat(`${name}: () => field("${name}"),`);
  } else {
    const renderArgument = (arg: GraphQLArgument): string => {
      return `argument("${arg.name}", variables.${arg.name})`;
    };

    // @todo restrict allowed Field types
    return args.length > 0
      ? `
      ${jsDocComment}
      ${name}:(
        variables,
        select,
      ) => field("${name}", Object.entries(variables).map(([k, v]) => argument(k, v)) as any, selectionSet(select(${type.toString()}Selector))),
    `
      : `
      ${jsDocComment}
      ${name}: (
        select,
      ) => field("${name}", undefined as never, selectionSet(select(${type.toString()}Selector))),
    `;
  }
}
Example #25
Source File: selectors.ts    From tql with MIT License 5 votes vote down vote up
printSignature = (field: GraphQLField<any, any, any>): string => {
  const { name, args } = field;

  const type = outputType(field.type);

  const comments = [
    field.description && `@description ${field.description}`,
    field.deprecationReason && `@deprecated ${field.deprecationReason}`,
  ].filter(Boolean) as string[];

  const jsDocComment =
    comments.length > 0
      ? `
    /**
     ${comments.map((comment) => "* " + comment).join("\n")}
     */
    `
      : "";

  // @todo define Args type parameter as mapped type OR non-constant (i.e Array<Argument<...> | Argument<...>>)
  if (type instanceof GraphQLScalarType || type instanceof GraphQLEnumType) {
    return args.length > 0
      ? `${jsDocComment}\n readonly ${name}: <V extends { ${args
          .map(printVariable)
          .join(", ")} }>(variables: V) => Field<"${name}", [ ${args
          .map(printArgument)
          .join(", ")} ]>`
      : `${jsDocComment}\n readonly ${name}: () => Field<"${name}">`;
  } else {
    // @todo restrict allowed Field types
    return args.length > 0
      ? `
      ${jsDocComment}
      readonly ${name}: <V extends { ${args
          .map(printVariable)
          .join(", ")} }, T extends ReadonlyArray<Selection>>(
        variables: V,
        select: (t: I${type.toString()}Selector) => T
      ) => Field<"${name}", [ ${args
          .map(printArgument)
          .join(", ")} ], SelectionSet<T>>,
    `
      : `
      ${jsDocComment}
      readonly ${name}: <T extends ReadonlyArray<Selection>>(
        select: (t: I${type.toString()}Selector) => T
      ) => Field<"${name}", never, SelectionSet<T>>,
    `;
  }
}
Example #26
Source File: schema.ts    From Deep-Lynx with MIT License 5 votes vote down vote up
// each key in the metatype should be included on the input object as a field to be filtered on
    inputFieldsForMetatype(metatype: Metatype): {[key: string]: any} {
        const fields: {[key: string]: any} = {};

        metatype.keys?.forEach((metatypeKey) => {
            const propertyName = stringToValidPropertyName(metatypeKey.property_name);

            switch (metatypeKey.data_type) {
                // because we have no specification on our internal number type, we
                // must set this as a float for now
                case 'number': {
                    fields[propertyName] = {
                        type: GraphQLFloat,
                    };
                    break;
                }

                case 'boolean': {
                    fields[propertyName] = {
                        type: GraphQLBoolean,
                    };
                    break;
                }

                case 'string' || 'date' || 'file': {
                    fields[propertyName] = {
                        type: GraphQLString,
                    };
                    break;
                }

                case 'list': {
                    fields[propertyName] = {
                        type: new GraphQLList(GraphQLJSON),
                    };
                    break;
                }

                case 'enumeration': {
                    const enumMap: {[key: string]: GraphQLEnumValueConfig} = {};

                    if (metatypeKey.options) {
                        metatypeKey.options.forEach((option) => {
                            enumMap[option] = {
                                value: option,
                            };
                        });
                    }

                    // we have to include a UUID here so that we can insure a uniquely named type
                    fields[propertyName] = {
                        type: new GraphQLEnumType({
                            name: stringToValidPropertyName(`${metatype.name}_${metatypeKey.name}_Enum_Type_B`),
                            values: enumMap,
                        }),
                    };
                    break;
                }

                default: {
                    fields[propertyName] = {
                        type: GraphQLString,
                    };
                }
            }
        });

        return fields;
    }
Example #27
Source File: Writer.ts    From graphql-ts-client with MIT License 5 votes vote down vote up
protected typeRef(
        type: GraphQLType,
        objectRender?: string | ((type: GraphQLObjectType | GraphQLInterfaceType, field: GraphQLField<any, any>) => boolean)
    ) {
        if (type instanceof GraphQLScalarType) {
            const mappedType = 
                (this.config.scalarTypeMap ?? EMPTY_MAP)[type.name] 
                ?? SCALAR_MAP[type.name];
            if (mappedType === undefined) {
                throw new Error(`Unknown scalar type ${type.name}`);
            }
            if (typeof mappedType === 'string') {
                this.text(mappedType);
            } else {
                this.text(mappedType.typeName);
            }
        } else if (type instanceof GraphQLObjectType || 
            type instanceof GraphQLInterfaceType ||
            type instanceof GraphQLUnionType
        ) {
            if (typeof objectRender === "string") {
                this.text(objectRender);
            } else if (type instanceof GraphQLUnionType) {
                this.enter("BLANK");
                for (const itemType of type.getTypes()) {
                    this.separator(" | ");
                    this.text(itemType.name);    
                }
                this.leave();
            } else if (typeof objectRender === 'function') {
                this.scope({type: "BLOCK", multiLines: true}, () => {
                    const fieldMap = type.getFields();
                    for (const fieldName in fieldMap) {
                        const field = fieldMap[fieldName];
                        if (objectRender(type, field)) {
                            this.separator(", ");
                            this.text("readonly ");
                            this.text(fieldName);
                            this.text(": ");
                            this.typeRef(field.type, objectRender);
                        }
                    }
                });
            } else {
                this.text(type.name);
            }
        } else if (type instanceof GraphQLEnumType || type instanceof GraphQLInputObjectType) {
            this.text(type.name);
        } else if (type instanceof GraphQLNonNull) {
            this.typeRef(type.ofType, objectRender);
        } else if (type instanceof GraphQLList) {
            if (type.ofType instanceof GraphQLNonNull) {
                if (!this.config.arrayEditable) {
                    this.text("readonly ");
                }
                this.typeRef(type.ofType, objectRender);
                this.text("[]");
            } else {
                if (!this.config.arrayEditable) {
                    this.text("Readonly");
                }
                this.text("Array<");
                this.typeRef(type.ofType, objectRender);
                this.text(" | undefined>");
            }
        }
    }
Example #28
Source File: codeGeneration.ts    From amplify-codegen with Apache License 2.0 5 votes vote down vote up
typeDeclarationForGraphQLType(type: GraphQLType) {
    if (type instanceof GraphQLEnumType) {
      this.enumerationDeclaration(type);
    } else if (type instanceof GraphQLInputObjectType) {
      this.structDeclarationForInputObjectType(type);
    }
  }
Example #29
Source File: Writer.ts    From graphql-ts-client with MIT License 5 votes vote down vote up
write() {
        this.prepareImportings();
        this.imported = true;
        for (const importStatement of this.importStatements) {
            this.stream.write(importStatement);
            this.stream.write("\n");
        }
        for (const importedType of this.importedTypes) {
            const behavior = this.importingBehavior(importedType);
            if (behavior === 'SELF') {
                continue;
            }
            if (behavior === 'SAME_DIR') {
                this.stream.write(`import type {${importedType.name}} from '.';\n`);
            } else {
                let subDir: string;
                if (importedType instanceof GraphQLInputObjectType) {
                    subDir = "inputs"; 
                } else if (importedType instanceof GraphQLEnumType) {
                    subDir = "enums"; 
                } else {
                    subDir = "fetchers";
                }
                if (this.isUnderGlobalDir()) {
                    this.stream.write(`import type {${importedType.name}} from './${subDir}';\n`);    
                } else {
                    this.stream.write(`import type {${importedType.name}} from '../${subDir}';\n`);
                }
            }
        }
        if (this.importedScalarTypes.size !== 0) {
            const sourcePrefix = this.isUnderGlobalDir() ? "../" : "../../";
            for (const [importSource, typeNames] of this.importedScalarTypes) {
                this.stream.write(`import type { ${Array.from(typeNames).join(", ")} } from '${sourcePrefix}${importSource}';\n`);
            }
        }
        if (this.importStatements.size !== 0 || this.importedTypes.size !== 0 || this.importedScalarTypes.size !== 0) {
            this.stream.write("\n");
        }
        this.writeCode();
    }