如何在本地发出“ graphql”请求?

时间:2019-06-14 01:32:43

标签: graphql apollo apollo-client

我正在nodejs应用程序中使用apollo graphql库。我想测试graphql query在单个过程中的工作方式。下面是我的源代码。

const cache = new InMemoryCache();

const client = new ApolloClient({
  cache,
  resolvers: {
    Query: {
      cart: (parent, args, context, info) => {
        console.log('resolvers:', args);
        return { name: 'prod2' };
      },
      visibilityFilter: () => {
        return 'hahahah';
      }
    }
  }
});

client
  .query({
    query: gql`
      {
        # visibilityFilter @client
        cart @client {
          products
        }
      }
    `
  })
  .then((ret) => console.log('client query:', ret))
  .catch((err) => console.error('client query error:', err));

cache.writeData({
  data: {
    todos: [],
    visibilityFilter: 'SHOW_ALL',
    networkStatus: {
      __typename: 'NetworkStatus',
      isConnected: false
    },
    cart: { products: 'prod1', __typename: 'Product' }
  }
});

我得到的错误是:

lient query error: Error: Network error: Error writing result to store for query:
 {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","variableDefinitions":[],"directives":[],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"cart"},"arguments":[],"directives":[{"kind":"Directive","name":{"kind":"Name","value":"client"},"arguments":[]}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"products"},"arguments":[],"directives":[]},{"kind":"Field","name":{"kind":"Name","value":"__typename"}}]}}]}}],"loc":{"start":0,"end":108}}
Store error: the application attempted to write an object with no provided typename but the store already contains an object with typename of Product for the object of id $ROOT_QUERY.cart. The selectionSet that was trying to be written is:
{"kind":"Field","name":{"kind":"Name","value":"cart"},"arguments":[],"directives":[{"kind":"Directive","name":{"kind":"Name","value":"client"},"arguments":[]}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"products"},"arguments":[],"directives":[]},{"kind":"Field","name":{"kind":"Name","value":"__typename"}}]}}

我想要查询name内的cart字段,但它返回null。如何使其在本地工作?

0 个答案:

没有答案