0

I have been trying to use GraphQL for a couple weeks now and am still yet to make a single resolver relationship work out. I'm using ExpressJS as the server.

I want something as simple as a User has Posts, and when you do a User query then you can also see their Posts as a sub-field. In my experience, the User is able to be retrieved but the Posts always return null.

This is the same for if I try and put Comments on a Post, then the Post can be returned but Comments or the User who made the Post return null.

Is anyone able to provide some type of code to be able to make a relationship like this work? The GraphQL docs all focus on relationships like the Library > Books > Author, but even if I try that, the second level down will return null like in this case.

I've made the following simplest Resolvers:

users() {
 return users;
},
User: {
 posts(parent) {
 return posts.filter((post) => post.userId === parent.id);
 }
}

With the following schema:

type User {
 id: ID!
 name: String!
 posts: [Post]
}
type Post {
 id: ID!
 title: String!
 content: String!
 userId: ID!
}
type Query {
 users: [User]
}

and the User can come back, but the Posts will be null.

{
 "data": {
 users": [
 {
 "id": "1",
 "name": "Alice",
 "posts": null
 },
asked May 20, 2024 at 15:31
3
  • your user resolver looks fine - what does post.filter((post) => post.userId === parent.id) result in on the server? Commented May 20, 2024 at 18:17
  • @MichelFloyd I'm not sure how to find out what it results in on the server. If I have an console.log(posts.filter((post) => post.userId === '1')) for example, it will log the correct result. But if I put a log in the resolver next to the return I never see that log happen. A User's Posts are always null when actually using it in a GraphQL setting Commented May 20, 2024 at 20:55
  • That's weird - it should pick up posts from the User resolver. You might need to include your server code - there's not enough here to go on. Commented May 21, 2024 at 17:11

0

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.