如何从在每个组件中创建一个阿波罗客户端过渡到在整个应用程序中重用同一客户端?

时间:2018-10-02 11:59:22

标签: apollo react-apollo

我目前正在使用apollo客户端的每个组件中执行此操作:

const username = getUsername();
const jwtToken = yield call(getJwtToken, username);

const link = new HttpLink({
    uri: getGraphqlEndpointUrl,
    headers: {
        'x-api-key': getApiKey(),
        'Authorization': jwtToken,
    },
});
const client = new ApolloClient({
    link: link,
    cache: new InMemoryCache(),
});

但是我只想创建一个客户端,以便可以使用缓存。我在想这样的事情:

index.tsx

import { ApolloProvider } from 'react-apollo';
import { createApolloClient } from './apollo';
const apolloClient = createApolloClient();
...
    return (
        <ApolloProvider client={apolloClient}>
            <Provider store={store}>
                <ConnectedRouter history={history}>
                    <ScrollToTop>
                        <App />
                    </ScrollToTop>
                </ConnectedRouter>
            </Provider>
        </ApolloProvider>
    );

apollo / index.tsx

import { ApolloClient } from 'apollo-client';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { getUsername, getJwtToken } from '../model/user';
import { getGraphqlEndpointUrl } from '../model/aws';

const httpLink = createHttpLink({
    uri: getGraphqlEndpointUrl,
});

const authLink = setContext((_, { headers }) => {
    const username = getUsername();
    if (username) {
        getJwtToken(username).then(function(jwtToken: string) {
            return {
                headers: {
                    ...headers,
                    authorization: jwtToken,
                }
            };
        });
    }
});

function createApolloClient() {
    const client = new ApolloClient({
        link: authLink.concat(httpLink),
        cache: new InMemoryCache()
    });

    return client;
}

export { createApolloClient };

现在我有几个问题:

  • 在之前创建客户端的sagas中,现在如何引用客户端?
  • apollo/index.tsx代码看起来正确吗?

0 个答案:

没有答案