How to use the parse function from graphql

Find comprehensive JavaScript graphql.parse code examples handpicked from public code repositorys.

graphql.parse is a function in the GraphQL.js library that parses a GraphQL query string into an abstract syntax tree (AST).

148
149
150
151
152
153
154
155
156
157
    return Promise.resolve('Hello world!')
  }
}
var query = '{ hello }'
var source = new graphql.Source(query)
var documentAST = graphql.parse(source)

agent.startTransaction('foo')

graphql.execute(schema, documentAST, rootValue).then(function (response) {
fork icon211
star icon536
watch icon296

+ 23 other calls in file

75
76
77
78
79
80
81
82
83
84

// given a "GraphQL schema language" text file, converts into introspection JSON
function introspect (text) {
  return new Promise(function (resolve, reject) {
    try {
      var astDocument = GraphQL.parse(text)
      var schema = GraphQL.buildASTSchema(astDocument)
      GraphQL.graphql({ schema, source: graphqlviz.query })
        .then(function (data) {
          resolve(data)
fork icon56
star icon682
watch icon14

How does graphql.parse work?

graphql.parse is a function provided by the graphql package that takes a GraphQL language string and returns an abstract syntax tree (AST) representation of that string, which can be used for further processing. It parses the string according to the GraphQL language specification, and can be used to perform validation, introspection, or execution of GraphQL operations.

13
14
15
16
17
18
19
20
21
22
23
const { applyRateLimits } = require('./rate-limiting')
const schema = require('./schema')


const customParseFn = (...args) => {
  try {
    return parse(...args)
  } catch (error) {
    // Identify parse errors so that customFormatErrorFn will allow them to be returned to the user.
    throw new GraphQLError(
      error.message,
fork icon33
star icon66
watch icon0

30
31
32
33
34
35
36
37
38
  return;
}
const quasi = node.quasi.quasis[0];
try {
  const filename = path.basename(context.getFilename());
  const ast = graphql.parse(new graphql.Source(quasi.value.cooked, filename));

  // we are not validating Relay usages here (relay/rule-graphql-syntax does it already)
  // but we are trying to be quite benevolent here
fork icon7
star icon53
watch icon5

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const { parse } = require("graphql");

const query = `
query GetBook($id: ID!) {
book(id: $id) {
title
author
published
}
}
`;

const ast = parse(query);
console.log(ast);

In this example, the graphql.parse function is used to parse a GraphQL query defined in the query variable. The resulting Abstract Syntax Tree (AST) is stored in the ast variable, and then logged to the console.

6
7
8
9
10
11
12
13
14
15
const internals = {};


// Inspired by graphql-tools
exports.makeExecutableSchema = ({ schema, resolvers = {}, preResolve }) => {
  const parsed = Graphql.parse(schema);
  const astSchema = Graphql.buildASTSchema(parsed, { commentDescriptions: true, assumeValidSDL: true });

  for (const resolverName of Object.keys(resolvers)) {
    const type = astSchema.getType(resolverName);
fork icon11
star icon34
watch icon2

212
213
214
215
216
217
218
219
220
221
const modelsFolder = path.resolve(outputPath, 'models');

process.stdout.write(`Generating models from ${generatedSchema} into ${modelsFolder} .. `);

try {
  const schema = parse(schemaContent);
  const schemaDoc = loadSchema(generatedSchema);
  const schemaPreTransformDoc = buildASTSchema(schema);
  const eslint = new ESLint({
    cwd: path.resolve(__dirname, '..'),
fork icon2
star icon14
watch icon2

+ 3 other calls in file

2
3
4
5
6
7
8
9
10
11
/**
 * Builds Graphql schema with
 * support for extending type definitions
 */
module.exports = function(typeDefs) {
  let astDocument = parse(typeDefs);
  let schema = buildASTSchema(astDocument);

  let extensionsAst = extractExtensionDefinitions(astDocument);
  if (extensionsAst.definitions.length > 0) {
fork icon0
star icon29
watch icon2

297
298
299
300
301
302
303
304
305
  if (processed?.request != null) {
    ctx.operationName = processed.request.operationName;
    ctx.request.operationName = processed.request.operationName;
    ctx.request.variables = processed.request.variables;

    ctx.document = parse(processed.request.query);
    ctx.operation = getOperationAST(ctx.document, ctx.operationName);
  }
},
fork icon0
star icon9
watch icon0

+ 18 other calls in file

65
66
67
68
69
70
71
72
73
74
  VariablesAreInputTypesRule,
  VariablesInAllowedPositionRule
];

function validatePseudoFragment(pseudoFragment) {
  const document = parse(`
    fragment ${pseudoFragment.name.value} on AllTypes {
      anyFieldName
    }
  `);
fork icon1
star icon6
watch icon2

+ 3 other calls in file

7
8
9
10
11
12
13
14
15
16
exports.isValid = async function (query) {
  let valid = true;
  // Parse the query
  let documentAST;
  try {
    documentAST = parse(query);
  } catch (error) {
    console.error("Invalid GraphQL query:", error.message);
    return false;
  }
fork icon0
star icon3
watch icon0

10
11
12
13
14
15
16
17
18
19
  })

// select and format all the data from the schema that we need for the docs
// used in the build step by script/graphql/build-static-files.js
module.exports = async function processSchemas (idl, previewsPerVersion) {
  const schemaAST = parse(idl.toString())
  const schema = buildASTSchema(schemaAST)

  // list of objects is used when processing mutations
  const objectsInSchema = schemaAST.definitions.filter(def => def.kind === 'ObjectTypeDefinition')
fork icon0
star icon2
watch icon0

29
30
31
32
33
34
35
36
37
38
}

function getSchema() {
  try {
    return buildASTSchema(
      parse(
        `
          directive @include(if: Boolean) on FRAGMENT | FIELD
          directive @skip(if: Boolean) on FRAGMENT | FIELD
          ${fs.readFileSync(getLocations().schema, 'utf8')}
fork icon0
star icon0
watch icon3

144
145
146
147
148
149
150
151
152
153
  schema: GraphQLSchema,
  schemaExtensions: Array<string>,
): GraphQLSchema {
  return GraphQL.extendSchema(
    schema,
    GraphQL.parse(schemaExtensions.join('\n')),
  );
}

function extendASTSchema(
fork icon0
star icon0
watch icon2

85
86
87
88
89
90
91
92
93
94
try {
    if (graphql.isSchema(fileExport)) {
        return fileExport;
    }
    if (isSchemaText(fileExport)) {
        return graphql.parse(fileExport);
    }
    if (isWrappedSchemaJson(fileExport)) {
        return graphql.buildClientSchema(fileExport.data);
    }
fork icon0
star icon0
watch icon1

15
16
17
18
19
20
21
22
23
24
25
26
27
// Read schema to string
fs=require('fs');
var SCHEMA = fs.readFileSync('/dev/stdin').toString();


// Parse schema to node graph
var parsed = GraphQL.parse(SCHEMA);


//console.log(parsed);



fork icon0
star icon0
watch icon0

+ 3 other calls in file

667
668
669
670
671
672
673
674
675
676
  // this isn't used to get the itemQueryName and we don't know it here
  pluralGraphQLName: ''
}).itemQueryName}(where: { id: $id }) { ${sessionData} } }`;
let ast;
try {
  ast = graphql.parse(query);
} catch (err) {
  throw new Error(`The query to get session data has a syntax error, the sessionData option in your createAuth usage is likely incorrect\n${err}`);
}
const errors = graphql.validate(base.schema, ast);
fork icon0
star icon0
watch icon0

+ 4 other calls in file

1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
  variableDefinitions
} = typesForLists.getVariablesForGraphQLField(field);
const rootName = getRootTypeName(field.type);
return async (args, query, context) => {
  var _result$errors;
  const selectionSet = graphql$1.parse(`fragment x on ${rootName} {${query}}`).definitions[0].selectionSet;
  const document = {
    kind: graphql$1.Kind.DOCUMENT,
    definitions: [{
      kind: graphql$1.Kind.OPERATION_DEFINITION,
fork icon0
star icon0
watch icon0

38
39
40
41
42
43
44
45
46
47
    const base64 = Buffer.from(p1).toString('base64');
    return `"getContextValue_${base64}"`;
  }
);

const queryAst = parse(queryBody);
const map = queryAst.definitions[0].selectionSet.selections.map(
  (selection) => {
    const name = selection.name.value;
    const alias = selection.alias ? selection.alias.value : name;
fork icon0
star icon0
watch icon1

+ 63 other calls in file