如何在 react-apollo 中模拟 GraphQL API 以进行离线 API 调用

How to mock GraphQL API in react-apollo for offline API calling

我正在使用 apollo 客户端在我的 React 应用程序中模拟 graphql api。这是我的 index.js(由 create-react-app 创建的 React 应用程序)

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import InventoryList from './components/InventoryList';
import Header from './components/Header';
import Footer from './components/Footer';
import Settings from './components/Settings';
import registerServiceWorker from './registerServiceWorker';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import { ApolloClient } from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { ApolloProvider } from 'react-apollo';
import { mockNetworkInterfaceWithSchema } from 'apollo-test-utils';
import {typeDefs} from './components/schema';
import { makeExecutableSchema, addMockFunctionsToSchema } from 'graphql-tools';

const schema = makeExecutableSchema({ typeDefs });
addMockFunctionsToSchema({ schema });

const mockNetworkInterface = mockNetworkInterfaceWithSchema({ schema });

const client = new ApolloClient({
  // By default, this client will send queries to the
  //  `/graphql` endpoint on the same host
  // Pass the configuration option { uri: YOUR_GRAPHQL_API_URL } to the `HttpLink` to connect 
  // to a different host

  link: new HttpLink({ uri: 'http://localhost:3000/graphql'}),
  networkInterface: mockNetworkInterface,
  cache: new InMemoryCache(),
});

// Requesting data
client.query({ query: gql`{ hello }` }).then(console.log);

ReactDOM.render(
  <ApolloProvider client={client}>
    <Router>
      <div>
        <Header />
        <Route exact path="/" component={App} />
        <Route exact path="/inventory" component={InventoryList} />
        <Route exact path="/settings" component={Settings} />
        <Footer />
      </div>
    </Router>
  </ApolloProvider>,
  document.getElementById('root')
)
registerServiceWorker();

这是我的组件LoggedInUser(应用组件的子组件)-

import React from 'react';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
import {typeDefs} from './schema';
import { makeExecutableSchema, addMockFunctionsToSchema } from 'graphql-tools';

const schema = makeExecutableSchema({ typeDefs });
addMockFunctionsToSchema({ schema });

const usersListQuery = gql`
  query UsersListQuery {
    users {
      id
      name
    }
  }
`;

function LoggedInUsers({ data: { users, refetch, loading, error } }) {
  return (
    <div>
      {/*<button onClick={() => refetch()}>
        Refresh
      </button> */}
      <ul>
        {users && users.map(user => (
          <li key={user.id}>
            {user.name}
          </li>
        ))}
      </ul>
    </div>
  );
}

export default graphql(usersListQuery)(LoggedInUsers);

我只是对如何点击 mock API 感到困惑,因为目前我收到控制台错误: POST http://localhost:3000/graphql 404(未找到)

我正在学习本教程 - https://dev-blog.apollodata.com/full-stack-react-graphql-tutorial-582ac8d24e3b

我觉得这个定义很奇怪。特别是在 Apollo Client 选项中彼此相邻的 linknetworkInterface 的定义。

const client = new ApolloClient({
  link: new HttpLink({ uri: 'http://localhost:3000/graphql'}),
  networkInterface: mockNetworkInterface,
  cache: new InMemoryCache(),
});

A​​pollo 的界面最近发生了变化。在 Apollo Client > 2.0 中,客户端采用单个 link。 link 是一个接受查询和 returns 结果的适配器。在 2.0 之前,客户端会使用网络接口,这是一个类似的概念,但会暗示执行网络请求。另一方面,链接不必发出网络请求或假装发出网络请求。此外,它们可以更容易地组合,并且已经开发了许多不同的 link。看来您使用的 Apollo Client 版本高于 2.0。 项目 apollo-test-utils seems to be mostly abandoned. It seems to be replaced by apollo-link-schema. The mocking section 描述了如何使用 link 模拟数据。