我刚开始在NodeJs中使用GraphQl。我了解类型解析器在以下示例中的编码位置。
但是我无法弄清楚解析器用于关系类型的位置。例如,下面的“类型书”具有一个属性作者,如果查询该属性,该属性应返回“作者”类型。我在哪里放置解析器来解析该书的作者?
// 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
}))
答案 0 :(得分:1)
您需要为Book类型定义特定的解析器。我建议您以这种方式从graphql-tools那里抢走makeExecutableSchema
,这样您就可以轻松构建所需的关系解析器。我已复制并更改您的解决方案以实现所需的结果。
const graphqlHTTP = require("express-graphql")
const express = require("express");
const { makeExecutableSchema } = require("graphql-tools")
const typeDefs = `
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 resolvers = {
Book: {
author: (rootValue, args) => {
// rootValue is a resolved Book type.
return {
id: "id",
name: "dan",
age: "20"
}
}
},
Query: {
books: (rootValue, args) => {
return [{ id: "id", name: "name", genre: "shshjs" }];
},
authors: (rootValue, args) => {
return Author.find({});
},
book: (rootValue, { id }) => {
return Book.findById(id);
},
author: (rootValue, { id }) => {
return Author.findById(id);
}
}
}
const app = express();
app.listen(5000, () => {
console.log('listening for request');
})
app.use('/graphql', graphqlHTTP({
schema: makeExecutableSchema({ typeDefs, resolvers }),
graphiql: true
}))