Reputation: 1887
I am just getting started with GraphQl in NodeJs. I understand where the resolvers for type goes as coded in below sample.
But I am unable to figure out where the resolver goes for relation Types. for example, Type Book below has a property author which is supposed to return Author type if queried. Where do I put the resolver to resolve this author for the book?
// 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
}))
Upvotes: 1
Views: 977
Reputation: 3825
You would need to define specific resolvers for the Book type. I would suggest going and grabbing makeExecutableSchema
from graphql-tools this way you can easily build the relation resolvers you require. I have copied and change your solution to achieve the desired outcome.
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
}))
Upvotes: 2