2

I'm building a graphql interface using golang. I'm using gqlgen package to implement it. Here I need to pass all field names in a query to get it in response, But the problem is my data is huge, it is having more than 30 fields it would be difficult to pass all fields in a query. This is my query

{Model{id, name, email, mobile,...............}}

Like this I need to pass all fields name.

Instead Im looking for a result which will return all fields without passing any fields. I mean if not passing any field names it should return all.

For example

{Model{}}
Deepak Deepu
  • 31
  • 1
  • 3

1 Answers1

1

First, you really should list out all the fields in your query. That is the nature of graphql. It is verbose, but most client libraries get the fields from your data structure anyway, so it's not that bad.

So I recommend listing out all fields manually!

Using Scalars (must be on v0.11.3 or below, see https://github.com/99designs/gqlgen/issues/1293)

But if you insist, if there is a will, there is way. You can use GraphQL's scalar types and make your own. See this doc for how to make them with gqlgen: https://gqlgen.com/reference/scalars/

In your schema, you can make a JSON scalar:

scalar JSON

type Query {
  random: JSON!
}

Make a model for this

// in your own models.go
// You can really play with this to make it better, easier to use
type JSONScalar json.RawMessage

// UnmarshalGQL implements the graphql.Unmarshaler interface
func (y *JSONScalar) UnmarshalGQL(v interface{}) error {
    data, ok := v.(string)
    if !ok {
        return fmt.Errorf("Scalar must be a string")
    }

    *y = []byte(data)
    return nil
}

// MarshalGQL implements the graphql.Marshaler interface
func (y JSONScalar) MarshalGQL(w io.Writer) {
    _, _ = w.Write(y)
}

Then link the scalar to your custom type in the gql.yml

models:
  JSON:
    model: github.com/your-project/path/graph/model.JSONScalar

When you run the generate (use gqlgen v0.11.3 or below, gqlgen version), your resolvers will now use the custom type you made. And it's easy to use:

func (r *queryResolver) random(ctx context.Context) (model.JSONScalar, error) {
    // something is the data structure you want to return as json
    something := struct {
        Value string
    }{
        Value: "Hello World",
    }

    d, _ := json.Marshal(something)
    return model1.JSONScalar(d), nil
}

The resulting query of

// Query
{
  random
}

// Response
{
  "random" : {
    "Value": "Hello World!"
   }
}
Steven Masley
  • 634
  • 2
  • 9