【发布时间】:2020-03-17 12:07:18
【问题描述】:
我刚刚开始在 NodeJs 中使用 GraphQl。我了解类型的解析器在下面的示例中编码。
但我无法弄清楚解析器用于关系类型的位置。例如,下面的 Type Book 有一个属性 author ,如果被查询,它应该返回 Author 类型。我在哪里放置解析器来解析本书的作者?
// Construct a schema, using GraphQL schema language
var schema = buildSchema(`
type Book {
id: ID!
name: String!
genre: String!
author: Author
}
type Author {
id: ID!
name: String!
age: String!
}
type Query {
books: [Book]
authors: [Author]
book(id: ID): Book
author(id: ID): Author
}
`);
const root = {
books: () => {
return Book.find({});
},
authors: () => {
return Author.find({});
},
book:({id}) => {
return Book.findById(id);
},
author:({id}) => {
return Author.findById(id);
}
}
const app = express()
app.listen(5000, () =>{
console.log('listening for request');
})
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true
}))
【问题讨论】:
-
我相信是的。我在将 graphqlHTTP 设置为 express 的中间件时使用这个 rootValue: root。我正在扩展这些示例graphql.org/graphql-js/running-an-express-graphql-server
-
目前官方文档非常缺乏。你真的shouldn't be using buildSchema in the first place。
-
@DanielRearden 真棒。你给了我我想要的东西。这解决了我的很多问题。谢谢