GraphQL 如何正确实现链解析器?
GraphQL 的主要概念之一是能够选择我们感兴趣的数据,同时省略不必要的字段。为了实现这一点,我们可以使用解析器。每个此类负责提供特定类型的数据。
我创建了一个小例子来展示我的问题。 它返回的错误是:
“不能为不可为 null 的字段 Parent.child 返回 null。”
我可以让父级创建整个对象,但是解析委托的好处在哪里,创建子级解析器以及解析器链的整个 GraphQL 概念有什么意义呢?
如何让父级调用子级解析器来解析其子级字段?
const { ApolloServer, gql } = require('apollo-server');
const typeDefs = gql`
type Child {
name: String!
}
type Parent {
name: String!
child: Child!
}
type Query {
getParent: Parent!
}
`;
(async function () {
const server = new ApolloServer({
typeDefs,
resolvers: {
Query: {
getParent: () => {
return {
name: "parent",
};
},
},
Child: {
name: () => "child",
},
}
});
await server.listen();
})();
One of the main concepts of GraphQL is being able to select the data we're interested in, while omitting the unnecessary fields. To achieve that we can use resolvers. Each such is responsible for providing data for a particular type.
I've created a small example to present my problem.
The error it returns is:
"Cannot return null for non-nullable field Parent.child."
I could just let the Parent create the whole object, but then where's the benefit of resolving delegation, what would be the point of creating the Child resolver and then the whole GraphQL concept of resolver chains?
How to make the parent call the Child resolver to resolve its child field?
const { ApolloServer, gql } = require('apollo-server');
const typeDefs = gql`
type Child {
name: String!
}
type Parent {
name: String!
child: Child!
}
type Query {
getParent: Parent!
}
`;
(async function () {
const server = new ApolloServer({
typeDefs,
resolvers: {
Query: {
getParent: () => {
return {
name: "parent",
};
},
},
Child: {
name: () => "child",
},
}
});
await server.listen();
})();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以下是您应该如何编写解析器:
我也是 gql 的初学者,但我会给出我的想法。
当您定义新的 ObjectType:Parent 时,如果您有嵌套的 ObjectType,则应为其编写 ObjectField 解析器,这意味着您应编写特定于该对象及其子级解析器函数的解析器。这样,嵌套对象就可以找到获取数据的方法。
查询和变异只是两个特殊的入口点。
参考这个: https://graphql.org/learn/schema /#查询和突变类型
Here is how you should write your resolver:
I'm also a beginner in gql, but I will give my thoughts.
When you define a new ObjectType:Parent, you should write the ObjectField Resolver for it if you have nested ObjectType, which means you should write the resolver specific the Object and its child's resolver function. that way , the nested object could found the way to fetch the data.
The Query and Mutation is just two special entry point.
refer to this: https://graphql.org/learn/schema/#the-query-and-mutation-types