升级到apollo-server-express 2.0.0上下文丢失

时间:2018-08-15 03:15:35

标签: express graphql apollo-server express-graphql

升级之前,我们已经

import express from 'express';
import { graphqlExpress, graphiqlExpress } from 'apollo-server-express';

const app = express();

app.use(
   '/graphql',
   bodyParser.json(),
   graphqlExpress(req => ({
   schema,
   tracing: true,
   context: { req },
 })),
);

app.use(
 '/graphiql',
 graphiqlExpress({
   endpointURL: '/graphql',
 }),
);

在我们的解析器中,我们可以获取请求并按如下所示设置req.session.token

const customResover = {
Query: {
   custom: async (root, args, context) => {
   console.log(' resolver called with args', args);
   const { req } = context;  
   ... fetch token info and set 
   req.session.token = ${token};
   ...

但是随着版本2.0.0的升级,代码更改为以下代码,我不确定如何修复CustomResolver,设置会话令牌以及如何实现上述目标的任何想法?

import express from 'express';
import { ApolloServer, gql } from 'apollo-server-express';
import { typeDefs, resolvers } from './schema/';

const app = express();
const apollo = new ApolloServer({
   typeDefs
   resolvers,
   engine: false
});

apollo.applyMiddleware({
   app,
});

1 个答案:

答案 0 :(得分:1)

https://www.apollographql.com/docs/apollo-server/migration-two-dot.html#request-headers

const apollo = new ApolloServer({
  typeDefs
  resolvers,
  context: ({ req }) => ({ req })
  engine: false
});

解决了这个问题,但Cookie出现问题,令牌无法到达浏览器。