2

我的 sampleJSON -

{
 "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}
  })
});

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

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

       }
    ]
  }

}

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

4

1 回答 1

0

回答太晚了,但如果你偶然发现这一点,你可以!使用GraphQLNonNull().

这是不可为空整数的示例

random: {
  type: new GraphQLNonNull(GraphQLInt)
}
于 2021-11-17T03:42:13.840 回答