Answer the question
In order to leave comments, you need to log in
How to implement recursive handlers in GraphQL on node.js?
There are two data types whose properties refer to each other:
type Query {
posts: [Post]
user(id: Int!): User
}
type Post {
id: Int
message: String
author: User
}
type User {
id: Int
name: String
posts: [Post]
}
{
posts {
id
message
author {
id
name
posts {
id
message
author {
id
name
}
}
}
}
}
const posts = [{ id: 0, message: 'foo', author: 0 }]
const users = [{ id: 0, name: 'bar', posts: [0] }]
const rootValue = {
posts: () => {
return posts
.map(post => ({
id: post.id,
message: post.message,
author: rootValue.user({ id: post.author })
}))
},
user: ({ id }) =>
users
.filter(user => user.id === id)
.map(user => ({ id: user.id, name: user.name, posts: [] }))[0]
}
Answer the question
In order to leave comments, you need to log in
const posts = [{ id: 0, message: 'foo', author: 0 }]
const users = [{ id: 0, name: 'bar', posts: [0] }]
const resolvers = {
User: {
posts({ id }) {
return posts.filter(post => (
post.author === id
))
}
},
Post: {
author({ author }) {
return users.find(user => (
user.id === author
))
}
},
posts() {
return posts;
},
users() {
return users;
}
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question