Graphql,如何返回空数组而不是 null

Rob*_*zzi 4 graphql

我是 Graphql 的新手,我想知道是否有办法在关系中返回空数组而不是 null 。让我们选择 User 和 Post 的经典示例

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

Type Post {
  id: ID!
  comment: String!
}
Run Code Online (Sandbox Code Playgroud)

当我对没有任何帖子的用户进行查询时,我希望在 posts 属性上有一个空数组,但现在我得到了null,我该怎么做?提前致谢。

Ben*_*jie 6

这需要在您的 GraphQL 模式(而不是您的 GraphQL 查询)中完成 - 您的 GraphQL 字段解析器应该返回一个数组而不是 null,并且(可选)指定它返回的数组为非 null;例如:

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

const resolvers = {
  User: {
    posts(user, _args, { getPosts }) {
      return (await getPosts({user_id: user.id})) || [];
    }
  }
}
Run Code Online (Sandbox Code Playgroud)