vektah/gqlparser

AST String method

Closed this issue · 5 comments

Would like a method to generate the string representation of an AST object that could be directly used in a query. For example, if had a Field that was generated from

object(id:$id){ id name value subobject(index:9){ id name }}

would like to be able to call something like

ast.String(field)

to return an equivalent string.

I wrote a utility function to do this in my own project, but it is specific to ast.Field and doubt it covers all possible definitions:

func fieldQueryString(field *ast.Field) string {
	query := field.Name
	if len(field.Arguments) > 0 {
		query += "("
		for _, arg := range field.Arguments {
			query += arg.Name + ":"
			query += field.Arguments.ForName(arg.Name).Value.String()
		}
		query += ")"
	}
	if len(field.SelectionSet) > 0 {
		query += "{"
		for _, f := range field.SelectionSet {
			field := f.(*ast.Field)
			query += fieldQueryString(field) + ","
		}
		query += "}"
	}

	return query
}

I think this would be generally useful for logging/debugging.

Apologies if this already exists, please point to where it is found if exists.

Opening issue in this repo as suggested in 99designs/gqlgen#723.

Added in #103

Thank you! Appreciate it.

Hello @vektah @scraymondjr !

How can I use formatter for getting query string from *ast.Field?

@vektah
Understood how it is possible. Thank you!