如何在graphql中获取响应中的所有字段而不在查询中传递任何字段名称 使用标量必须在 v0.11.3 或更低版本上,请参阅 https://github.com/99designs/gqlgen/issues/1293

问题描述

我正在使用 golang 构建一个 graphql 界面。我正在使用 gqlgen 包来实现它。 在这里,我需要在查询中传递所有字段名称获取响应,但问题是我的数据很大,它有 30 多个字段,很难在查询中传递所有字段。 这是我的查询

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

像这样我需要传递所有字段名称

相反,我正在寻找一个结果,该结果将返回所有字段而不传递任何字段。我的意思是如果不传递任何字段名称,它应该返回所有。

例如

{Model{}}

解决方法

首先,您确实应该列出查询中的所有字段。这就是 graphql 的本质。它很冗长,但大多数客户端库无论如何都会从您的数据结构中获取字段,所以这还不错

所以我建议手动列出所有字段!

使用标量(必须在 v0.11.3 或更低版本上,请参阅 https://github.com/99designs/gqlgen/issues/1293

但如果你坚持,如果有意愿,就有办法。您可以使用 GraphQL 的标量类型并创建自己的标量类型。请参阅此文档以了解如何使用 gqlgen 制作它们:https://gqlgen.com/reference/scalars/

在您的架构中,您可以创建一个 JSON 标量:

scalar JSON

type Query {
  random: JSON!
}

为此做一个模型

// 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)
}

然后将标量链接到 gql.yml

中的自定义类型
models:
  JSON:
    model: github.com/your-project/path/graph/model.JSONScalar

当您运行 generate(使用 gqlgen v0.11.3 或更低版本,gqlgen version)时,您的解析器现在将使用您创建的自定义类型。而且它易于使用:

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
}

结果查询

// Query
{
  random
}

// Response
{
  "random" : {
    "Value": "Hello World!"
   }
}