我目前正在使用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 };
现在我有几个问题:
apollo/index.tsx
代码看起来正确吗?