在生成 GraphQL 模型时跳过一些字段

huangapple go评论77阅读模式
英文:

Skip some fields in generating GraphQl models

问题

我在我的Golang项目中使用gqlgen库来从GraphQl文件生成解析器和模型。
在我的项目中,我使用一种机制来从由gqlgen生成的模型生成查询。

当该模型没有与自身关联的字段(循环)时,所有的事情都是正确的。

我正在寻找一种方法来不生成那些字段,换句话说,我不需要那些字段在模型中。我只需要它的解析器。

例如,这是我的GraphQl文件:

type Menu {
    ID: Int!
    SubMenu: Menu!
}

这是生成的模型:

type Menu struct {
    ID      int     `json:"ID"`
    SubMenu *Menu   `json:"Product"`
}

我只需要SubMenu字段的解析器。所以我的gqlgen.yml文件如下:

models:
  Menu:
    fields:
      SubMenu:
          resolver: true

有没有办法告诉gqlgen跳过生成模型中的某些字段?或者你有其他处理方法吗?

英文:

I use gqlgen library in my Golang project to generate resolvers and models from GraphQl files.
In my project, I use a mechanism to generate a query from models generated by gqlgen.

All things are true when that model doesn't have relational fields with himself(circle).

I'm looking for some way to don't generate those fields, In other words, I don't need that fields to be in the model. I need only its resolvers.

for example, this is my GraphQl file:

type Menu {
    ID: Int!
    SubMenu: Menu!
}

and this is the generated model:

type Menu struct {
	ID           int            `json:"ID"`
	SubMenu      *Menu       `json:"Product"`
}

I need only the resolvers for the SubMenu field. So my gqlgen.yml file is the same as:


models:
  Menu:
    fields:
      SubMenu:
          resolver: true


Is there any way to tell the gqlgen to skip some fields in generating models? Or do you have another solution to handle it?

答案1

得分: 2

你可以在你的 gqlgen.yml 中配置模型生成的位置,例如:

model:
  filename: graph/model/models_gen.go
  package: model

但这并不意味着你不能在与生成的文件(这里是 model)相同的包中添加自己的文件。因此,你可以在这些文件中自定义你的模型,并且在模型生成过程中它们将保持不变。此外,gqlgen 代码生成不会尝试生成已经存在于包中的模型结构体。

例如,使用上面的示例,如果你在 gqlgen.yml 中指定的文件之外的文件中在 model 包中声明了自己的 Menu 结构体,它将不会在生成的文件中生成 Menu 模型结构体的代码。

示例代码可以在以下链接中找到:

https://github.com/99designs/gqlgen/tree/master/example/starwars/models

英文:

You can configure where the model will be generated in your gqlgen.yml such as:

model:
  filename: graph/model/models_gen.go
  package: model

But it does not mean you cannot add your own files in the same package as the one generated(here model). Therefore you can customize your model in these files and they will stay untouched during model generation. Also gqlgen code generation will not try to generate model struct that already exist in the package.

For instance, with the above example, if you declare your own Menu struct within the package model in a different file than the one specified in the gqlgen.yml it will not generate code for the model struct Menu in the generated file.

Example

https://github.com/99designs/gqlgen/tree/master/example/starwars/models

huangapple
  • 本文由 发表于 2021年7月29日 11:41:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/68569775.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定