Graphql, how to return empty array instead of null

2019-06-10 02:04发布

问题:

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:

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})) || [];
    }
  }
}


标签: graphql