graphql-dotnet / parser

A lexer and parser for GraphQL in .NET
MIT License
216 stars 43 forks source link

Pretty print graphql query? #365

Closed clement911 closed 11 months ago

clement911 commented 1 year ago

Is it possible to use this package to pretty print a graphql query? By pretty-print, I mean that it should format it with indentation, similar to how GraphiQL can prettify the query.

Shane32 commented 1 year ago

Yes; see the example in the readme here.

clement911 commented 12 months ago

The example you pointed out seems to output in a format that is not graphql. My goal is to output the same query passed as input, except with indentation.

Shane32 commented 12 months ago

Try the code sample; it will work. The sample output immediately above doesn’t correspond with the code sample.

Shane32 commented 12 months ago

(The sample output is of StructurePrinter but you want the SDLPrinter which is what the code sample uses.)

Shane32 commented 12 months ago

Feel free to post a PR that clarifies the readme file. It should probably have a section discussing the SDLPrinter with sample input and output, and a list of available options.

clement911 commented 12 months ago

You're right it works. The sample is correct except I had to remove the using (GraphQLDocument doesn't implement IDisposable).

Thank you @Shane32

clement911 commented 12 months ago

If anyone else is looking, the following code is simpler:

public static string Prettify(string query)
{
    var document = Parser.Parse(query);
    return new SDLPrinter().Print(document);
}
clement911 commented 11 months ago

I'm reopening this issue and it seems we've found a potential bug. When prettifying a mutation, the mutation keyword is removed from the output.

string query = Prettify("mutation { bulkOperationCancel { bulkOperation { id } } }");

Result:

{
  bulkOperationCancel {
    bulkOperation {
      id
    }
  }
}
Shane32 commented 11 months ago

Opened new issue. Pretty significant bug. Should be a quick fix though.