R
R
Rinor2019-01-27 02:54:04
Node.js
Rinor, 2019-01-27 02:54:04

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]
}

How should the handlers look like so that the next request would work correctly?
{
  posts {
    id
    message
    author {
      id
      name
      posts {
        id
        message
        author {
          id
          name
        }
      }
    }
  }
}

There is currently the following implementation, but user.posts is always empty and hence the request fails.
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

1 answer(s)
V
Vladlen Hellsite, 2019-01-27
@Rinor

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 question

Ask a Question

731 491 924 answers to any question