Skip to content

Access query/mutation/subscription as string in Resolve function #254

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
gabrielruiu opened this issue Oct 24, 2017 · 1 comment
Closed

Comments

@gabrielruiu
Copy link

gabrielruiu commented Oct 24, 2017

Is there a possibility to access the string representation of the query/mutation/subscription performed, within the Resolve function?

Example:
Somebody performs the following mutation:

mutation {
  someMutation {
    result {
      a
      b
    }
  }
}
someMutation := &graphql.Field{
    Type: graphql.NewNonNull(someMutationPayload),
    Resolve: func(p graphql.ResolveParams) (interface{}, error) {
        mutationQuery := convertToString(p) //then mutationQuery == "someMutation{result{a b}}"
     },
}
@gabrielruiu
Copy link
Author

gabrielruiu commented Oct 24, 2017

Figured it out in the meantime:

func convertFieldsToString(fields []*ast.Field) string {
    var queryAsString string
    for _, field := range fields {
        queryAsString = queryAsString + field.Name.Value
        selectionsAsString := convertFieldSelectionsToString(field)
        if selectionsAsString != "" {
            queryAsString = queryAsString + "{" + selectionsAsString + "}"
        }
    }
    return queryAsString
}

func convertFieldSelectionsToString(field *ast.Field) string {
    var selectionsAsString string
    if field.SelectionSet != nil {
        selections := field.SelectionSet.Selections
        for _, selection := range selections {
            selectionAsField := selection.(*ast.Field)
            if selectionAsField.SelectionSet != nil {
                selectionsAsString = selectionsAsString + " " + convertFieldsToString([]*ast.Field{selectionAsField}) + " "
            } else {
                selectionsAsString = selectionsAsString + " " + selectionAsField.Name.Value + " "
            }
        }
       return selectionsAsString
    }
    return ""
}

And just call it from the Resolve function

someMutation := &graphql.Field{
    Type: graphql.NewNonNull(someMutationPayload),
    Resolve: func(p graphql.ResolveParams) (interface{}, error) {
        mutationQuery := convertFieldsToString(p.Info.FieldASTs)
     },
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant