graphql#Kind TypeScript Examples

The following examples show how to use graphql#Kind. 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: generate-query.ts    From graphql-query-generator with MIT License 6 votes vote down vote up
function getVariable(argName: string, varName: string): ArgumentNode {
  return {
    kind: Kind.ARGUMENT,
    loc,
    name: getName(argName),
    value: {
      kind: Kind.VARIABLE,
      name: getName(varName)
    }
  }
}
Example #2
Source File: require-description.ts    From graphql-eslint with MIT License 6 votes vote down vote up
function getNodeName(node: SelectorNode) {
  const DisplayNodeNameMap = {
    [Kind.OBJECT_TYPE_DEFINITION]: 'type',
    [Kind.INTERFACE_TYPE_DEFINITION]: 'interface',
    [Kind.ENUM_TYPE_DEFINITION]: 'enum',
    [Kind.SCALAR_TYPE_DEFINITION]: 'scalar',
    [Kind.INPUT_OBJECT_TYPE_DEFINITION]: 'input',
    [Kind.UNION_TYPE_DEFINITION]: 'union',
    [Kind.DIRECTIVE_DEFINITION]: 'directive',
  } as const;

  switch (node.kind) {
    case Kind.OBJECT_TYPE_DEFINITION:
    case Kind.INTERFACE_TYPE_DEFINITION:
    case Kind.ENUM_TYPE_DEFINITION:
    case Kind.SCALAR_TYPE_DEFINITION:
    case Kind.INPUT_OBJECT_TYPE_DEFINITION:
    case Kind.UNION_TYPE_DEFINITION:
      return `${DisplayNodeNameMap[node.kind]} ${node.name.value}`;
    case Kind.DIRECTIVE_DEFINITION:
      return `${DisplayNodeNameMap[node.kind]} @${node.name.value}`;
    case Kind.FIELD_DEFINITION:
    case Kind.INPUT_VALUE_DEFINITION:
    case Kind.ENUM_VALUE_DEFINITION:
      return `${node.parent.name.value}.${node.name.value}`;
    case Kind.OPERATION_DEFINITION:
      return node.name ? `${node.operation} ${node.name.value}` : node.operation;
  }
}
Example #3
Source File: custom-date.scalar.ts    From Cromwell with MIT License 6 votes vote down vote up
CustomDateScalar = new GraphQLScalarType({
    name: "CustomDateScalar",
    description: "Custom implementation of Date scalar",
    parseValue(value: string) {
        try {
            return new Date(value);
        } catch (error) { }
        return null;
    },
    serialize(value: Date) {
        try {
            return value.toISOString()
        } catch (e) { }
        return null;
    },
    parseLiteral(ast) {
        if (ast.kind === Kind.STRING) {
            return new Date(ast.value);
        }
        if (ast.kind === Kind.INT) {
            return new Date(parseInt(ast.value, 10));
        }
        return null;
    },
})
Example #4
Source File: generate-query.ts    From graphql-query-generator with MIT License 6 votes vote down vote up
function getQueryOperationDefinition(
  schema: GraphQLSchema,
  config: InternalConfiguration
): {
  queryDocument: OperationDefinitionNode
  variableValues: { [varName: string]: any }
} {
  const node = schema.getQueryType().astNode
  const {
    selectionSet,
    variableDefinitionsMap,
    variableValues
  } = getSelectionSetAndVars(schema, node, config)

  // Throw error if query would be empty
  if (selectionSet.selections.length === 0) {
    throw new Error(
      `Could not create query - no selection was possible at the root level`
    )
  }

  return {
    queryDocument: {
      kind: Kind.OPERATION_DEFINITION,
      operation: 'query',
      selectionSet,
      variableDefinitions: Object.values(variableDefinitionsMap),
      loc,
      name: getName('RandomQuery')
    },
    variableValues
  }
}
Example #5
Source File: ts-artifacts.ts    From graphql-mesh with MIT License 6 votes vote down vote up
function buildSignatureBasedOnRootFields(
  codegenHelpers: CodegenHelpers,
  type: Maybe<GraphQLObjectType>,
  namespace: string
): Record<string, string> {
  if (!type) {
    return {};
  }

  const fields = type.getFields();
  const operationMap: Record<string, string> = {};
  for (const fieldName in fields) {
    const field = fields[fieldName];
    const argsExists = field.args && field.args.length > 0;
    const argsName = argsExists ? `${namespace}.${type.name}${field.name}Args` : '{}';
    const parentTypeNode: NamedTypeNode = {
      kind: Kind.NAMED_TYPE,
      name: {
        kind: Kind.NAME,
        value: type.name,
      },
    };

    operationMap[fieldName] = `  /** ${field.description} **/\n  ${
      field.name
    }: InContextSdkMethod<${namespace}.${codegenHelpers.getTypeToUse(
      parentTypeNode
    )}['${fieldName}'], ${argsName}, ${unifiedContextIdentifier}>`;
  }
  return operationMap;
}
Example #6
Source File: objectid-scalar.ts    From convoychat with GNU General Public License v3.0 6 votes vote down vote up
ObjectIdScalar = new GraphQLScalarType({
  name: "ObjectId",
  description: "Mongo object id scalar type",
  parseValue(value: string) {
    return new ObjectId(value); // value from the client input variables
  },
  serialize(value: ObjectId) {
    return value.toHexString(); // value sent to the client
  },
  parseLiteral(ast) {
    if (ast.kind === Kind.STRING) {
      return new ObjectId(ast.value); // value from the client query
    }
    return null;
  },
})
Example #7
Source File: appsync-visitor.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
constructor(
    protected _schema: GraphQLSchema,
    rawConfig: TRawConfig,
    additionalConfig: Partial<TPluginConfig>,
    defaultScalars: NormalizedScalarsMap = DEFAULT_SCALARS,
  ) {
    super(rawConfig, {
      ...additionalConfig,
      scalars: buildScalars(_schema, rawConfig.scalars || '', defaultScalars),
      target: rawConfig.target,
      isTimestampFieldsAdded: rawConfig.isTimestampFieldsAdded,
      handleListNullabilityTransparently: rawConfig.handleListNullabilityTransparently,
      usePipelinedTransformer: rawConfig.usePipelinedTransformer,
      transformerVersion: rawConfig.transformerVersion,
    });

    const typesUsedInDirectives: string[] = [];
    if (rawConfig.directives) {
      const directiveSchema = parse(rawConfig.directives);
      directiveSchema.definitions.forEach((definition: DefinitionNode) => {
        if (definition.kind === Kind.ENUM_TYPE_DEFINITION || definition.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION) {
          typesUsedInDirectives.push(definition.name.value);
        }
      });
    }

    this.typesToSkip = [this._schema.getQueryType(), this._schema.getMutationType(), this._schema.getSubscriptionType()]
      .filter(t => t)
      .map(t => (t && t.name) || '');
    this.typesToSkip.push(...typesUsedInDirectives);
  }
Example #8
Source File: gqlTypes.ts    From ra-data-prisma with MIT License 6 votes vote down vote up
operationDefinition = (
  operation: OperationTypeNode,
  selectionSet: SelectionSetNode,
  name: NameNode,
  variableDefinitions: VariableDefinitionNode[],
): OperationDefinitionNode => ({
  kind: Kind.OPERATION_DEFINITION,
  operation,
  selectionSet,
  name,
  variableDefinitions,
})
Example #9
Source File: global-id.scalar.ts    From nestjs-relay with MIT License 6 votes vote down vote up
parseLiteral(ast: ValueNode): ResolvedGlobalId {
    if (ast.kind !== Kind.STRING) {
      throw new GraphQLError(`Invalid ID type: ${ast.kind}`);
    }
    const { id, type } = fromGlobalId(ast.value);
    if (!id || !type) {
      throw new GraphQLError(`Invalid ID: ${ast.value}`);
    }
    return new ResolvedGlobalId({ type, id });
  }
Example #10
Source File: Variables.ts    From tql with MIT License 6 votes vote down vote up
buildVariableDefinitions = <T extends SelectionSet<any>>(
  schema: GraphQLSchema,
  root: OperationTypeNode,
  selectionSet: T
): Array<VariableDefinition<any, any>> => {
  const variableDefinitions: VariableDefinition<any, any>[] = [];
  const typeInfo = new TypeInfo(schema);

  // @note need to wrap selectionset in an operation (root) for TypeInfo to track correctly
  const operationDefinition = operation(
    root,
    "",
    selectionSet,
    variableDefinitions
  );

  const visitor = visitWithTypeInfo(typeInfo, {
    [Kind.ARGUMENT]: (node) => {
      const type = typeInfo.getArgument()?.astNode?.type!;

      if (node.value.kind === "Variable") {
        // define the `VariableDefinition`
        variableDefinitions.push(variableDefinition(node.value, type));
      }
    },
  });

  // @todo return from here
  visit(operationDefinition, visitor);

  return variableDefinitions;
}
Example #11
Source File: naming-convention.ts    From graphql-eslint with MIT License 6 votes vote down vote up
KindToDisplayName = {
  // types
  [Kind.OBJECT_TYPE_DEFINITION]: 'Type',
  [Kind.INTERFACE_TYPE_DEFINITION]: 'Interface',
  [Kind.ENUM_TYPE_DEFINITION]: 'Enumerator',
  [Kind.SCALAR_TYPE_DEFINITION]: 'Scalar',
  [Kind.INPUT_OBJECT_TYPE_DEFINITION]: 'Input type',
  [Kind.UNION_TYPE_DEFINITION]: 'Union',
  // fields
  [Kind.FIELD_DEFINITION]: 'Field',
  [Kind.INPUT_VALUE_DEFINITION]: 'Input property',
  [Kind.ARGUMENT]: 'Argument',
  [Kind.DIRECTIVE_DEFINITION]: 'Directive',
  // rest
  [Kind.ENUM_VALUE_DEFINITION]: 'Enumeration value',
  [Kind.OPERATION_DEFINITION]: 'Operation',
  [Kind.FRAGMENT_DEFINITION]: 'Fragment',
  [Kind.VARIABLE_DEFINITION]: 'Variable',
}
Example #12
Source File: gqlTypes.ts    From ra-data-prisma with MIT License 5 votes vote down vote up
selectionSet = (
  selections: SelectionNode[],
): SelectionSetNode => ({
  kind: Kind.SELECTION_SET,
  selections,
})
Example #13
Source File: generate-query.ts    From graphql-query-generator with MIT License 5 votes vote down vote up
function getName(name: string): NameNode {
  return {
    kind: Kind.NAME,
    value: name
  }
}
Example #14
Source File: gqlTypes.ts    From ra-data-prisma with MIT License 5 votes vote down vote up
nonNullType = (
  type: NamedTypeNode | ListTypeNode,
): NonNullTypeNode => ({
  kind: Kind.NON_NULL_TYPE,
  type,
})
Example #15
Source File: input-name.ts    From graphql-eslint with MIT License 5 votes vote down vote up
isObjectType = (node: ObjectTypeNode): boolean =>
  [Kind.OBJECT_TYPE_DEFINITION, Kind.OBJECT_TYPE_EXTENSION].includes(node.type)
Example #16
Source File: gqlTypes.ts    From ra-data-prisma with MIT License 5 votes vote down vote up
field = (
  name: NameNode,
  optionalValues: Partial<FieldNode> = {},
): FieldNode => ({
  kind: Kind.FIELD,
  name,
  ...optionalValues,
})
Example #17
Source File: generate-query.ts    From graphql-query-generator with MIT License 5 votes vote down vote up
function isMandatoryType(type: TypeNode): boolean {
  return type.kind === Kind.NON_NULL_TYPE
}
Example #18
Source File: index.ts    From graphql-mesh with MIT License 5 votes vote down vote up
async getCodeFirstSource({
    schema: schemaConfig,
  }: YamlConfig.GraphQLHandlerCodeFirstConfiguration): Promise<MeshSource> {
    if (schemaConfig.endsWith('.graphql')) {
      const rawSDL = await readFileOrUrl<string>(schemaConfig, {
        cwd: this.baseDir,
        allowUnknownExtensions: true,
        importFn: this.importFn,
      });
      const schema = buildSchema(rawSDL);
      return {
        schema,
      };
    } else {
      // Loaders logic should be here somehow
      const schemaOrStringOrDocumentNode = await loadFromModuleExportExpression<GraphQLSchema | string | DocumentNode>(
        schemaConfig,
        { cwd: this.baseDir, defaultExportName: 'schema', importFn: this.importFn }
      );
      let schema: GraphQLSchema;
      if (schemaOrStringOrDocumentNode instanceof GraphQLSchema) {
        schema = schemaOrStringOrDocumentNode;
      } else if (typeof schemaOrStringOrDocumentNode === 'string') {
        schema = buildSchema(schemaOrStringOrDocumentNode);
      } else if (
        typeof schemaOrStringOrDocumentNode === 'object' &&
        schemaOrStringOrDocumentNode?.kind === Kind.DOCUMENT
      ) {
        schema = buildASTSchema(schemaOrStringOrDocumentNode);
      } else {
        throw new Error(
          `Provided file '${schemaConfig} exports an unknown type: ${util.inspect(
            schemaOrStringOrDocumentNode
          )}': expected GraphQLSchema, SDL or DocumentNode.`
        );
      }
      return {
        schema,
      };
    }
  }
Example #19
Source File: alphabetize.ts    From graphql-eslint with MIT License 5 votes vote down vote up
argumentsEnum: ('FieldDefinition' | 'Field' | 'DirectiveDefinition' | 'Directive')[] = [
  Kind.FIELD_DEFINITION,
  Kind.FIELD,
  Kind.DIRECTIVE_DEFINITION,
  Kind.DIRECTIVE,
]
Example #20
Source File: gqlTypes.ts    From ra-data-prisma with MIT License 5 votes vote down vote up
document = (definitions: DefinitionNode[]): DocumentNode => ({
  kind: Kind.DOCUMENT,
  definitions,
})
Example #21
Source File: alphabetize.ts    From graphql-eslint with MIT License 5 votes vote down vote up
variablesEnum: ['OperationDefinition'] = [Kind.OPERATION_DEFINITION]
Example #22
Source File: preset.ts    From amplify-codegen with Apache License 2.0 5 votes vote down vote up
generateSwiftPreset = (
  options: Types.PresetFnArgs<AppSyncModelCodeGenPresetConfig>,
  models: TypeDefinitionNode[],
): Types.GenerateOptions[] => {
  const config: Types.GenerateOptions[] = [];
  models.forEach(model => {
    const modelName = model.name.value;
    config.push({
      ...options,
      filename: join(options.baseOutputDir, `${modelName}.swift`),
      config: {
        ...options.config,
        scalars: { ...SWIFT_SCALAR_MAP, ...options.config.scalars },
        generate: 'code',
        selectedType: modelName,
      },
    });
    if (model.kind !== Kind.ENUM_TYPE_DEFINITION) {
      config.push({
        ...options,
        filename: join(options.baseOutputDir, `${modelName}+Schema.swift`),
        config: {
          ...options.config,
          target: 'swift',
          scalars: { ...SWIFT_SCALAR_MAP, ...options.config.scalars },
          generate: 'metadata',
          selectedType: modelName,
        },
      });
    }
  });

  // class loader
  config.push({
    ...options,
    filename: join(options.baseOutputDir, `AmplifyModels.swift`),
    config: {
      ...options.config,
      scalars: { ...SWIFT_SCALAR_MAP, ...options.config.scalars },
      target: 'swift',
      generate: 'loader',
    },
  });
  return config;
}
Example #23
Source File: alphabetize.ts    From graphql-eslint with MIT License 5 votes vote down vote up
selectionsEnum: ('OperationDefinition' | 'FragmentDefinition')[] = [
  Kind.OPERATION_DEFINITION,
  Kind.FRAGMENT_DEFINITION,
]
Example #24
Source File: graphql.ts    From amplify-codegen with Apache License 2.0 5 votes vote down vote up
typenameField = {
  kind: Kind.FIELD,
  name: { kind: Kind.NAME, value: '__typename' },
}
Example #25
Source File: gqlTypes.ts    From ra-data-prisma with MIT License 5 votes vote down vote up
namedType = (name: NameNode): NamedTypeNode => ({
  kind: Kind.NAMED_TYPE,
  name,
})
Example #26
Source File: converter.ts    From graphql-eslint with MIT License 5 votes vote down vote up
export function convertToESTree<T extends DocumentNode>(node: T, schema?: GraphQLSchema) {
  const typeInfo = schema ? new TypeInfo(schema) : null;

  const visitor: ASTVisitor = {
    leave(node, key, parent) {
      const leadingComments: Comment[] =
        'description' in node && node.description
          ? [
              {
                type: node.description.block ? 'Block' : 'Line',
                value: node.description.value,
              },
            ]
          : [];

      const calculatedTypeInfo: TypeInformation | Record<string, never> = typeInfo
        ? {
            argument: typeInfo.getArgument(),
            defaultValue: typeInfo.getDefaultValue(),
            directive: typeInfo.getDirective(),
            enumValue: typeInfo.getEnumValue(),
            fieldDef: typeInfo.getFieldDef(),
            inputType: typeInfo.getInputType(),
            parentInputType: typeInfo.getParentInputType(),
            parentType: typeInfo.getParentType(),
            gqlType: typeInfo.getType(),
          }
        : {};

      const rawNode = () => {
        if (parent && key !== undefined) {
          return parent[key];
        }
        return node.kind === Kind.DOCUMENT
          ? <DocumentNode>{
              ...node,
              definitions: node.definitions.map(definition =>
                (definition as unknown as GraphQLESTreeNode<DefinitionNode>).rawNode()
              ),
            }
          : node;
      };

      const commonFields: Omit<GraphQLESTreeNode<typeof node>, 'parent'> = {
        ...node,
        type: node.kind,
        loc: convertLocation(node.loc),
        range: [node.loc.start, node.loc.end],
        leadingComments,
        // Use function to prevent RangeError: Maximum call stack size exceeded
        typeInfo: () => calculatedTypeInfo as any, // Don't know if can fix error
        rawNode,
      };

      return 'type' in node
        ? {
            ...commonFields,
            gqlType: node.type,
          }
        : commonFields;
    },
  };

  return visit(node, typeInfo ? visitWithTypeInfo(typeInfo, visitor) : visitor) as GraphQLESTreeNode<T>;
}
Example #27
Source File: render.ts    From tql with MIT License 5 votes vote down vote up
kindRevMapping = reverseRecord(Kind)
Example #28
Source File: alphabetize.ts    From graphql-eslint with MIT License 5 votes vote down vote up
fieldsEnum: ('ObjectTypeDefinition' | 'InterfaceTypeDefinition' | 'InputObjectTypeDefinition')[] = [
  Kind.OBJECT_TYPE_DEFINITION,
  Kind.INTERFACE_TYPE_DEFINITION,
  Kind.INPUT_OBJECT_TYPE_DEFINITION,
]
Example #29
Source File: global-id.scalar.spec.ts    From nestjs-relay with MIT License 5 votes vote down vote up
describe('ID Scalar', () => {
  let scalar: GlobalIdScalar;

  beforeEach(() => {
    scalar = new GlobalIdScalar();
  });

  describe('when a valid global id is provided', () => {
    it('should serialize correctly', () => {
      const globalId = new ResolvedGlobalId({ type: 'Object', id: '1' });
      expect(scalar.serialize(globalId)).toBe('T2JqZWN0OjE=');
    });
    it('should parseValue correctly', () => {
      expect(scalar.parseValue('T2JqZWN0OjE=')).toMatchObject(
        new ResolvedGlobalId({ type: 'Object', id: '1' }),
      );
    });
    it('should parseLiteral correctly', () => {
      expect(
        scalar.parseLiteral({
          value: 'T2JqZWN0OjE=',
          kind: Kind.STRING,
        }),
      ).toMatchObject(new ResolvedGlobalId({ type: 'Object', id: '1' }));
    });
  });

  describe('when an parsing an invalid global id', () => {
    describe('when a global id that does not have a colon symbol is provided', () => {
      it('should throw an error from the parseValue method', () => {
        expect(() => scalar.parseValue('T2JqZWN0MQ==')).toThrow('Invalid ID: T2JqZWN0MQ==');
      });
      it('should throw an error from the parseLiteral method', () => {
        expect(() =>
          scalar.parseLiteral({
            value: 'T2JqZWN0MQ==',
            kind: Kind.STRING,
          }),
        ).toThrow('Invalid ID: T2JqZWN0MQ==');
      });
    });
    describe('when a global id that does not have a type is provided', () => {
      it('should throw an error from the parseValue method', () => {
        expect(() => scalar.parseValue('OjE=')).toThrow('Invalid ID: OjE=');
      });
      it('should throw an error from the parseLiteral method', () => {
        expect(() =>
          scalar.parseLiteral({
            value: 'OjE=',
            kind: Kind.STRING,
          }),
        ).toThrow('Invalid ID: OjE=');
      });
    });
    describe('when a global id that does not have an id is provided', () => {
      it('should throw an error from the parseValue method', () => {
        expect(() => scalar.parseValue('T2JqZWN0Og==')).toThrow('Invalid ID: T2JqZWN0Og==');
      });
      it('should throw an error from the parseLiteral method', () => {
        expect(() =>
          scalar.parseLiteral({
            value: 'T2JqZWN0Og==',
            kind: Kind.STRING,
          }),
        ).toThrow('Invalid ID: T2JqZWN0Og==');
      });
    });
    describe('when a non-string value is provided', () => {
      it('should throw an error from the parseLiteral method', () => {
        expect(() =>
          scalar.parseLiteral({
            value: 'T2JqZWN0Og==',
            kind: Kind.INT,
          }),
        ).toThrow('Invalid ID type: IntValue');
      });
    });
  });
});