How to use the graphql.parse function in graphql

To help you get started, we’ve selected a few graphql examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github aws-amplify / amplify-cli / packages / graphql-transformer-core / src / collectDirectives.ts View on Github external
export function collectDirectives(sdl: string): DirectiveNode[] {
  const doc = parse(sdl);
  let directives = [];
  for (const def of doc.definitions) {
    switch (def.kind) {
      case Kind.OBJECT_TYPE_DEFINITION:
        // Does def node have a @model and no @auth.
        directives = directives.concat(collectObjectDirectives(def));
        break;
      case Kind.INTERFACE_TYPE_DEFINITION:
        directives = directives.concat(collectInterfaceDirectives(def));
        break;
      case Kind.UNION_TYPE_DEFINITION:
        directives = directives.concat(collectUnionDirectives(def));
        break;
      case Kind.INPUT_OBJECT_TYPE_DEFINITION:
        directives = directives.concat(collectInputObjectDirectives(def));
        break;
github accounts-js / accounts / packages / graphql-api / src / scripts / schema-to-types.ts View on Github external
async function introspectionFromSchema(schemaT: any /* GraphQLSchema */) {
  const queryAST = parse(introspectionQuery);
  const result = await execute(schemaT, queryAST);
  return result.data; /* IntrospectionQuery */
}
github gridsome / gridsome / gridsome / lib / graphql / page-query.js View on Github external
function processPageQuery (pageQuery) {
  const result = {
    query: undefined,
    variables: [],
    paginate: {
      fieldName: undefined,
      typeName: undefined
    },
    getFilters: () => {},
    getPerPage: () => PER_PAGE
  }

  const ast = pageQuery.query ? parse(pageQuery.query) : null

  result.query = ast && visit(ast, {
    Variable ({ name: { value: name }}) {
      if (name === 'page') return
      if (name === 'path') return

      const path = !NODE_FIELDS.includes(name)
        ? ['fields'].concat(name.split('__'))
        : [name]

      result.variables.push({ name, path })
    },
    Field (fieldNode) {
      return visit(fieldNode, {
        Directive (node, key, parent, path, ancestors) {
          if (node.name.value === 'paginate') {
github Urigo / graphql-modules / packages / epoxy / src / schema-mergers / merge-schema.ts View on Github external
const mutationType = schemaDef.mutation ? schemaDef.mutation : allTypes.find(t => t === 'Mutation');
    const subscriptionType = schemaDef.subscription ? schemaDef.subscription : allTypes.find(t => t === 'Subscription');
    schemaDef = {
      query: queryType,
      mutation: mutationType,
      subscription: subscriptionType,
    };
  }

  const schemaDefinition = createSchemaDefinition(schemaDef);

  if (!schemaDefinition) {
    return Object.values(mergedNodes);
  }

  return [...Object.values(mergedNodes), parse(schemaDefinition).definitions[0]];
}
github AEB-labs / cruddl / spec / regression / regression-suite.ts View on Github external
throw new Error(`Regression suite not set up correctly`);
        }

        const gqlPath = path.resolve(this.testsPath, name + '.graphql');
        const resultPath = path.resolve(this.testsPath, name + '.result.json');
        const variablesPath = path.resolve(this.testsPath, name + '.vars.json');
        let contextPath = path.resolve(this.testsPath, name + '.context.json');
        const metaPath = path.resolve(this.testsPath, name + '.meta.json');
        if (!fs.existsSync(contextPath)) {
            contextPath = path.resolve(this.path, 'default-context.json');
        }

        const gqlTemplate = fs.readFileSync(gqlPath, 'utf-8');
        const gqlSource = this.testDataEnvironment.fillTemplateStrings(gqlTemplate);

        const operations = parse(gqlSource).definitions
            .filter(def => def.kind == 'OperationDefinition') as OperationDefinitionNode[];
        this._isSetUpClean = this._isSetUpClean && !operations.some(op => op.operation == 'mutation');
        const hasNamedOperations = operations.length && operations[0].name;

        const expectedResultTemplate = JSON.parse(stripJsonComments(fs.readFileSync(resultPath, 'utf-8')));
        const expectedResult = this.testDataEnvironment.fillTemplateStrings(expectedResultTemplate);
        const variableValues = fs.existsSync(variablesPath) ? JSON.parse(stripJsonComments(fs.readFileSync(variablesPath, 'utf-8'))) : {};
        const context = fs.existsSync(contextPath) ? JSON.parse(stripJsonComments(fs.readFileSync(contextPath, 'utf-8'))) : {};
        const meta = fs.existsSync(metaPath) ? JSON.parse(stripJsonComments(fs.readFileSync(metaPath, 'utf-8'))) : {};

        if (meta.waitForArangoSearch) {
            await new Promise(resolve => setTimeout(resolve, 1000));
        }

        let actualResult: any;
        if (hasNamedOperations) {
github aws-amplify / amplify-cli / packages / graphql-transformer-core / src / TransformerContext.ts View on Github external
constructor(inputSDL: string) {
    const doc: DocumentNode = parse(inputSDL);
    for (const def of doc.definitions) {
      if (def.kind === 'OperationDefinition' || def.kind === 'FragmentDefinition') {
        throw new Error(`Found a ${def.kind}. Transformers accept only documents consisting of TypeSystemDefinitions.`);
      }
    }
    this.inputDocument = doc;
    this.fillNodeMapWithInput();
  }
github zalando-incubator / graphql-jit / src / __benchmarks__ / benchmarks.ts View on Github external
} from "./schema-many-resolvers";
import {
  query as nestedArrayQuery,
  schema as nestedArraySchema
} from "./schema-nested-array";

interface BenchmarkMaterial {
  query: DocumentNode;
  schema: GraphQLSchema;
  variables?: any;
}

const benchmarks: { [key: string]: BenchmarkMaterial } = {
  introspection: {
    schema: nestedArraySchema(),
    query: parse(getIntrospectionQuery({ descriptions: true }))
  },
  fewResolvers: {
    schema: fewResolversSchema(),
    query: fewResolversQuery,
    variables: { id: "2", width: 300, height: 500 }
  },
  manyResolvers: {
    schema: manyResolverSchema(),
    query: manyResolverQuery,
    variables: { id: "2", width: 300, height: 500 }
  },
  nestedArrays: {
    schema: nestedArraySchema(),
    query: nestedArrayQuery,
    variables: { id: "2", width: 300, height: 500 }
  }
github Shopify / graphql-tools-web / packages / graphql-validate-fixtures / src / index.ts View on Github external
operationSources.map((source) => {
      try {
        return parse(source);
      } catch (error) {
        throw new Error(
          `Error parsing '${source.name}':\n\n${error.message.replace(
            /Syntax Error.*?\(.*?\) /,
            '',
          )}`,
        );
      }
    }),
  );
github CMDco / subql / src / cabotage.js View on Github external
function parseSchema(schema) {
  if (!schema) {
    throw new Error('parseSchema :: parseSchema must take in a schema string');
  }
  storedSchema = schema;
  let schemaSource = new graphql.Source(schema);
  let parsedSchema = graphql.parse(schema);
  parsedSchema.definitions.forEach((ele) => {
    if (ele.name.value === 'Query' || ele.name.value === 'Mutation') {
      ele.fields.forEach((field) => {
        operations[field.name.value] = {
          name: field.name.value,
          type: ele.name.value,
          value: field.type.name.value
        }
      });
    }
  });
}
function findFields(obj, store) {
github dotansimha / graphql-binding / src / info.ts View on Github external
function extractQuerySelectionSet(
  query: string,
  typeName: string,
  schema: GraphQLSchema,
): SelectionSetNode {
  if (!query.startsWith('fragment')) {
    query = `fragment tmp on ${typeName} ${query}`
  }
  const document = parse(query)
  const errors = validate(schema, document).filter(
    e => e.message.match(/Fragment ".*" is never used./) === null,
  )
  if (errors.length > 0) {
    throw errors
  }

  const queryNode = document.definitions[0]
  if (!queryNode || queryNode.kind !== 'FragmentDefinition') {
    throw new Error(`Invalid query: ${query}`)
  }

  return queryNode.selectionSet
}