我试图看看是否有可能获取几个有自己的解析器的字段,并以某种方式将它们放在一个DB查询中,因为它们是从同一个地方获取的。
例如:图式
type ExampleResposne {
A: Int!
B: Int!
C: Int!
}The gqlgen.yml
models:
ExampleResponse:
fields:
A:
resolver: true
B:
resolver: true
C:
resolver: true现在我想从同一个DB调用中获取A和B,如果它们同时被请求的话
我有一个API,它根据键返回这些
exampleRes, err := resolver.service.GetExample(ctx, GetExampleRequest{
Keys: []ExampleKey{
AKey,
BKey,
},
})是这样的可能性,还是我应该重新考虑我的方法?
生成的解析器
func (r *exampleResponseResolver) A(ctx context.Context, obj *model.ExampleResponse) (int, error) { panic(fmt.Errorf("not implemented"))
}
func (r *exampleResponseResolver) B(ctx context.Context, obj *model.ExampleResponse) (int, error) { panic(fmt.Errorf("not implemented"))
}
func (r *exampleResponseResolver) C(ctx context.Context, obj *model.ExampleResponse) (int, error) { panic(fmt.Errorf("not implemented"))
}发布于 2022-08-30 10:11:12
你似乎有些话题混淆了:
数据采集
数据访问的概念是在一个解析器的函数/方法调用下处理多个数据请求。应该在解析类型级别而不是在该类型的单个字段级别上考虑这一点。
这方面的一个例子(取自https://gqlgen.com/reference/dataloaders/)是在一个数据库请求下解析多个Users。
Graphql字段解析器
在使用gqlgen.yml配置时,您已经为以下字段指定了单独的解析器:
models:
ExampleResponse:
fields:
A:
resolver: true
...字段解析器的概念旨在解决一个类型的单个字段,而不是作为一个整体来解析该类型,本质上与数据交换具有相反的效果。当我们试图解析议论文领域或代码拆分解析器逻辑时,这是非常有用的。
需要注意的是,字段解析器在没有有效使用时经常会导致N+1问题。
解决方案
您可能没有看到您的类型ExampleResponse的解析器,因为您需要在Query类型下追加查询入口点。
schema.graphql
type Query {
getExample: ExampleResposne
}然后运行:go run github.com/99designs/gqlgen generate
你应该看到:
func (r *queryResolver) GetExample(ctx context.Context) (*model.ExampleResponse, error) {
panic(fmt.Errorf("not implemented"))
}详情请参见https://graphql.org/learn/schema/#the-query-and-mutation-types。
https://stackoverflow.com/questions/73537888
复制相似问题