Apollo Server 2 with subscriptions using context

时间:2018-12-03 13:16:21

标签: express graphql apollo

I am trying to use context in my apollo server requesting user and headers. Everything works fine until I try to use subscriptons.

const app = express();

middlewares(app);

app.disable('x-powerd-by');

const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: ({ req }) => ({
    user: req.user,
    headers: req.headers.authorization
  }),
  playground: !IN_PROD
})

server.applyMiddleware({ app })

const ws = createServer(app);

server.installSubscriptionHandlers(ws);

ws.listen({ port: PORT }, () => {
  console.log(`Server ready at http://localhost:${PORT}${server.graphqlPath}`)
  console.log(`Subscriptions ready at ws://localhost:${PORT}${server.subscriptionsPath}`)
});

Here is the error I get when I try a subscription in playgorund

{
  "error": {
    "message": "Cannot read property 'user' of undefined"
  }
}

If I remove user from context I get the same error about headers. if I remove headers there is no error in subscription but I get unauthenticated while I try to make a mutation

SOLVED

const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: await ({ req }) => ({
    const user = req.user;
    const headers = req.headers.authorization;
    return {user, headers}
  }),
  playground: !IN_PROD
})

0 个答案:

没有答案