Graphql, how to return empty array instead of null

2019-06-10 01:32发布

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.

标签: graphql
1条回答
我想做一个坏孩纸
2楼-- · 2019-06-10 02:20

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})) || [];
    }
  }
}
查看更多
登录 后发表回答