Search code examples
javaformattinggraphqlgraphql-java

Prettify GraphQL query string in Java


I have a Java program which, among other things, reads raw GraphQL queries from XML files and sends them to a given endpoint via HTTP. The problem is that server accepts only proper formatted GraphQL queries, which means no extra spaces, newlines etc. are allowed. So basically I have to write them in a single line, because any newline symbol will break whole query by adding lots of spaces to match XML hierarchy (element containing query is not root element).

As you can tell, single-lined queries, especially long ones are not human-friendly and they're hard to read. There are a lot of code formatters/prettifyers here and there, online, inside IDEA, Postman, Insomnia etc, all of them can do it in a single button click.

Working XML file (one-lined query):

<request>
    <url>http://localhost:8080/graphql</url>
    <type>GRAPHQL</type>
    <body>mutation { login(input: {username: \"user\", password: \"12345\"}) {status}}</body>
</request>

Desired XML file (multi-line query):

<request>
    <url>http://localhost:8080/graphql</url>
    <type>GRAPHQL</type>
    <body>
        mutation {
          login(input: {username: "user", password: "12345"}) {
            status
          }
        }
    </body>
</request>

How can I deal with that scenario? Before sending, I should perform formatting on the 'body' string. Is there any 'prettification' library, or should I write custom symbols 'remover'?


Solution

  • graphql-java already come with AstPrinter that can pretty print a GraphQL AST node. So you can first convert the query string to the AST node and then use it to prettify the query string:

     String gql = "mutation { login(input: {username: \"user\", password: \"12345\"}) {status}}";
     Parser parser = new Parser();
     Document doc = parser.parseDocument(gql);
     System.out.println(AstPrinter.printAst(doc)); //which should print out a prettified query here