Graphql,如何返回空数组而不是 null [英] Graphql, how to return empty array instead of null

查看:26
本文介绍了Graphql,如何返回空数组而不是 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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!
}

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

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 模式(而不是你的 GraphQL 查询)中完成 - 你的 GraphQL 字段解析器应该返回一个数组而不是 null 并且(可选)指定它返回的数组是非空的;例如:

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,如何返回空数组而不是 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆