4

I'm new in Graphql and i'd like to know if there is a way to return an empty array instead of null in a relation. Let pick the classic example with User and Post

type User {
  id: ID!
  posts: [Post]
}

Type Post {
  id: ID!
  comment: String!
}

when i make a query on an user without any post i'd like to have an empty array on posts attribute, but now i get null, how can i do that? Thanks in advance.

1
  • In what server implementation language? Commented Dec 14, 2018 at 0:18

1 Answer 1

6

This needs to be done in your GraphQL schema (rather than your GraphQL query) - your GraphQL field resolver should return an array instead of null and (optionally) specify that the array it returns is non-null; for example:

const typeDefs = gql`
  type User {
    id: ID!
    posts: [Post!]!
  }
`;

const resolvers = {
  User: {
    posts(user, _args, { getPosts }) {
      return (await getPosts({user_id: user.id})) || [];
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.