Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse GraphQL request string into an object

I am running Apollo lambda server for GraphQL. I want to intercept the GraphQL query/mutation from the POST request body and parse it so I can find out which query/mutation the request is asking for. The environment is Node.js.

The request isn't JSON, it's GraphQL query language. I've looked around to try and find a way to parse this into an object that I can navigate but I'm drawing a blank.

The Apollo server must be parsing it somehow to direct the request. Does anyone know a library that will do this or pointers on how I can parse the request? Examples of request bodies and what I want to retrieve below.

{"query":"{\n  qQueryEndpoint {\n    id\n  }\n}","variables":null,"operationName":null}

I would like to identify that this is a query and that qQueryEndpoint is being asked for.

{"query":"mutation {\\n  saveSomething {\\n    id\\n  }\\n}","variables":null}

I would like to identify that this is a mutation and the saveSomething mutation is being used.

My first idea for this is to strip out the line breaks and try and use regular expressions to parse the request but it feels like a very brittle solution.

like image 478
Nick Ramsbottom Avatar asked Mar 01 '18 10:03

Nick Ramsbottom


People also ask

How do you parse a request in Graphql?

You could use graphql-js like so: const { parse, visit } = require('graphql'); const query = ` { books { ... rest of the query } } ` const ast = parse(query); const newAst = visit(ast, { enter(node, key, parent, path, ancestors) { // do some work }, leave(node, key, parent, path, ancestors) { // do some more work } });

What is Graphql AST?

When a GraphQL server receives a query to process it generally comes in as a single String. This string must be split into meaningful sub-strings (tokenization) and parsed into a representation that the machine understands. This representation is called an abstract syntax tree, or AST.


1 Answers

You can use graphql-tag :

const gql = require('graphql-tag');

const query = `
  {
    qQueryEndpoint {
      id
    }
  }
`;

const obj = gql`
  ${query}
`;

console.log('operation', obj.definitions[0].operation);
console.log('name', obj.definitions[0].selectionSet.selections[0].name.value);

Prints out :

operation query
name qQueryEndpoint

And with your mutation :

operation mutation
name saveSomething
like image 178
Gabriel Bleu Avatar answered Sep 20 '22 09:09

Gabriel Bleu