如何为apollo客户端的每个请求设置变量?

时间:2019-08-18 20:26:36

标签: reactjs apollo react-apollo

我正在使用apollo-client,并希望为每个请求发送一些变量。我们称之为locale。我不想将其传递给每个Query组件,这不是DRY模式。

2 个答案:

答案 0 :(得分:0)

您可以添加一个中间件链接,该链接将即时修改您的operation

  class MiddlewareLink extends ApolloLink {
    request (operation: Operation, forward: NextLink) {
      operation.variables['prop1'] = 'value1'

      return forward(operation)
    }
  }

  ...
  const client = new ApolloClient({
    link: ApolloLink.from([
      new MiddlewareLink(),
      httpLink
    ])
  })

这种方式目前看来是最正确的,也许以后apollo-link-http会得到扩展,并且能够从上下文中接受一些数据并传递给变量。

答案 1 :(得分:-1)

这可以通过使用中间件来实现:

import { ApolloClient } from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { ApolloLink, concat } from 'apollo-link';

const httpLink = new HttpLink({ uri: '/graphql' });

const authMiddleware = new ApolloLink((operation, forward) => {
  operation.setContext({
    headers: {
      locale: localStorage.getItem('locale') || 'en-US',
    }
  });

  return forward(operation);
})

const client = new ApolloClient({
  link: concat(authMiddleware, httpLink),
});

签出文档:https://www.apollographql.com/docs/react/advanced/network-layer/