使用ApolloClient进行远程数据和本地数据查询

时间:2018-11-27 19:44:38

标签: graphql apollo apollo-client

用于说明所需内容的最小代码。

import { ApolloClient } from 'apollo-client';
import {ApolloLink} from 'apollo-link';
import {withClientState} from 'apollo-link-state';
import {RestLink} from 'apollo-link-rest';
import { InMemoryCache } from 'apollo-cache-inmemory';
import gql from 'graphql-tag';


const defaults = {
  isActive: false,
}
const resolvers = {
};

const typeDefs = `
`;

const cache = new InMemoryCache();

const link = ApolloLink.from([
  withClientState({
    defaults,
    resolvers,
    cache,
    typeDefs
  }),
  new RestLink({ uri: ''}),
])

const client = new ApolloClient({
  link,
  cache,
});

const query = gql`
  query Users {
    users @rest(type: "Users", path: "data.json", method: "GET") {
      name
      frends
      isActive @client
    }
  }
`;

client.query({
  query, 
})
.then( ({data:{users}}) => {
  console.log(users); // [ {name: 'FirstUser', isActive: false, frends: [{name: FirstFrend}]} ] 
} );

我需要递归遍历数据树并向缓存添加其他属性。我只能对嵌套[ {name: 'FirstUser', isActive: false, frends: [{name: FirstFrend}]} ]进行第一级操作。但是在阿波罗的帮助下,递归地形成状态以获得类似的结构[ {name: 'FirstUser', isActive: false, frends: [{name: 'FirstFrend', isActive: false}]} ]frends的嵌套是事先未知的。可以有任意多个级别。

0 个答案:

没有答案