通过graphql查询可选的本地字段

时间:2019-09-29 23:02:47

标签: graphql apollo react-apollo apollo-client

使用GraphQL,我想查询仅在某些数组元素中找到的所有字段的整个数组。

假设我有以下数据和本地客户端:

// data1.json
[
  {
    "type": "title",
    "description": "Title!"
  },
  {
    "type": "person",
    "description": "He has been working in this office for 10 years."
    "name": "Thomas"
    "age": "35"
  },
  {
    "type": "office",
    "description": "Engineering"
    "size": "90"
    "budget": "1500000"
  },
]
import data1 from './data1.json'
import data2 from './data2.json' // same structure to data1
... // other imports

const client = new ApolloClient({
  cache: new InMemoryCache()
});

client.cache.writeData({
  data: {
    departments: [
      {
        name: 'departmentOne',
        data: data1.map(item => ({ ...item, __typename: 'element' })),
        __typename: 'department'
      },
      {
        name: 'departmentTwo',
        data: data2.map(item => ({ ...item, __typename: 'element' })),
        __typename: 'department'
      }
    ],
    __typename: 'departments'
  }
});

然后,在我的组件之一中,如何获取部门中的所有元素?

当我查询它时,它就可以工作了:

{
  departments @client {
    name
    data {
      type
      description
      __typename
    }
    __typename
  }
}

但是以下查询将不返回任何内容:

{
  departments @client {
    name
    data {
      type
      description
      name
      age
      size
      budget
      __typename
    }
    __typename
  }
}

我想为此需要添加一个本地解析器或typeDefs,但是它看起来如何?

首先,我不确定缓存是否具有所有阵列。由于某些元素中缺少某些字段(例如“名称”,“年龄”和其他字段),是否可以自动忽略数据?

0 个答案:

没有答案