【问题标题】:Return only non-null values from GraphQLList object仅从 GraphQLList 对象返回非空值
【发布时间】:2018-07-31 06:12:15
【问题描述】:

我的示例 JSON -

{
 "entries": [
    {
      "fields":{
        "title":"My test title"
      }
    },
    {
      "fields":{
        "description":"My test description"
    }
    }
 ]
}

Schema.js -

const rootQuery = new GraphQLObjectType({
   name: 'testQuery',
   fields: {
     Articles: {
       type: articleItem,
       resolve(parentValue) {
          return axios.get(`/getArticles`).then(resp => resp.data);
       }
     }
   }
});

const articleItem = new GraphQLObjectType({
   name: 'articleItem',
   fields: () => ({
    entries: {type: new GraphQLList(entry)}
   })
});

const entry = new GraphQLObjectType({
   name: 'entry',
   fields: () => ({
      fields: {type: fields}
   })
});

const fields = new GraphQLObjectType({
  name: 'fields',
  fields: () => ({
    title: {type: GraphQLString},
    description: {type: GraphQLString}
  })
});

GraphQL 查询我用来查询上述 JSON 中的数据 -

query articles{
    Articles {
        entries{
          fields{
            title,
            description
          }
        }
     }
}

我想知道为什么查询返回“title”,即使它在第二个对象中为空,并且在第一个对象中也有描述。有没有办法只返回不为空的“标题”或“描述”?

当前查询结果 -

{
  "data" : {
    "entries" [
       {
         "fields": {
             "title": "My test title",
             "description": null
         }
       },

       {
          "fields": {
             "title": null,
             "description" : "My test description"
          }

       }
    ]
  }

}

要求的结果 -

{
  "data" : {
    "entries" [
       {
         "fields": {
             "title": "My test title"
         }
       },

       {
          "fields": {
             "description" : "My test description"
          }

       }
    ]
  }

}

感谢您对此的任何帮助!,谢谢。

【问题讨论】:

    标签: graphql graphql-js express-graphql


    【解决方案1】:

    回答为时已晚,但如果您偶然发现此问题,您可以使用 GraphQLNonNull() 将其设为不可空 (!)。

    这是不可为空的整数的示例

    random: {
      type: new GraphQLNonNull(GraphQLInt)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-14
      • 1970-01-01
      • 2018-08-07
      • 2014-10-04
      • 2021-11-29
      相关资源
      最近更新 更多