从Apollo服务器检索非标头上下文

问题描述

我不断看到有关在Apollo Client上设置上下文的示例,例如:

new ApolloClient({
    uri: '...',request(operation) {
      const currentUser = readStore<CurrentUser>("currentUser");
      currentUser &&
        operation.setContext({
          headers: { authorization: currentUser.token },other: "things"
        });
    }
  });
}

带有转到请求标头的内容和“其他”内容。然而,经过2个多小时的研究,我找不到在Apollo Server的另一端检索其他上下文数据的示例。

似乎所有示例都与授权令牌有关,但是如何检索其余内容,例如使用apollo-server-express

这是我到目前为止所拥有的:

const apollo = new ApolloServer({
  typeDefs,resolvers,context({ req }): Context {
    const currentUser =
      (req.headers.authorization &&
        (jwt.verify(
          req.headers.authorization,process.env.JWTSIGN
        ) as Context["currentUser"])) ||
      null;

    // Ok for req.headers.authorization,how to I get "other: things" ?

    return {
      ip: req.ip,currentUser
    };
  }
});

此处的context函数仅从Express获取一个req和一个res对象。经过一些日志后,似乎没有包含我想要的数据。

谢谢。

解决方法

在您共享的示例中共享标题的唯一原因是,ApolloClient在其上下文中使用headers值填充了发出请求时发送的HTTP headers。然后,这些标头由express解析,并在req对象上可用。 ApolloClient使用的上下文严格是客户端的。 ApolloServer使用的上下文严格是服务器端的。您不能使用ApolloClient的上下文将任意值传递到服务器-您应该在GraphQL查询中使用标头或参数。