【发布时间】:2020-04-22 04:47:44
【问题描述】:
在用 JavaScript 为 GraphQL 编写库时,我偶然发现了一个奇怪的行为。我设法在一个非常简单的例子中隔离了它。让我们以这个服务器sn-p:
const { ApolloServer, gql } = require("apollo-server")
const typeDefs = gql`
type Book {
resolveItSelf: String
}
type Query {
book: Book
}
`
const resolvers = {
Query: {
book: () => {
return null // same behavior with undefined here
}
},
Book: {
resolveItSelf: () => "resolveItSelf"
}
}
const server = new ApolloServer({ typeDefs, resolvers })
server.listen().then(({ url }) => {
console.log(`???? Server ready at ${url}`)
})
如果我们使用以下查询查询此服务器:
{
book {
resolveItSelf
}
}
我们得到这个结果:
{
"data": {
"book": null
}
}
所以,我期待 graphql 执行器尝试解析“resolveItSelf”字段(它有自己的解析器),即使图书解析器返回 null。
获得我期望的行为的一种方法是稍微更改本书的解析器:
const resolvers = {
Query: {
book: () => {
return {} // empty object instead of null/undefined
}
},
Book: {
resolveItSelf: () => "resolveItSelf"
}
}
然后我们得到这个结果:
{
"data": {
"book": {
"resolveItSelf": "resolveItSelf"
}
}
}
即使父项为空,该字段也已解析!
所以我的问题是,为什么如果父解析器返回 null/undefined,即使请求的字段可以自己解析,graphql-js 执行程序也会停止尝试解析字段? (草案中是否有涉及这一点的部分?)
【问题讨论】:
标签: graphql graphql-js