I have this setup for ApolloServer with subscriptions. It is correctly connecting to my resolvers and returning data to the client. But, it isn’t yet sending Context data to the resolvers. I have my Context function in new ApolloServer()
, but the code in it never gets called. What am I missing?
import {ApolloServer} from '@apollo/server';
import {startStandaloneServer} from '@apollo/server/standalone'
import typeDefs from '/imports/apollo/schema';
import {resolvers} from "../imports/apollo/resolvers";
import {getUserIdByLoginToken} from "../imports/apollo/meteor-apollo-utils";
import {createServer} from 'http';
import { expressMiddleware } from '@apollo/server/express4';
import {ApolloServerPluginDrainHttpServer} from '@apollo/server/plugin/drainHttpServer';
import {makeExecutableSchema} from '@graphql-tools/schema';
import {WebSocketServer} from 'ws';
import {useServer} from 'graphql-ws/lib/use/ws';
import express from "express";
import cors from 'cors';
//https://www.apollographql.com/docs/apollo-server/data/subscriptions/
const app = express()
app.use(cors());
const httpServer = createServer(app);
const schema = makeExecutableSchema({typeDefs, resolvers});
// Creating the WebSocket server
const wsServer = new WebSocketServer({
// This is the `httpServer` we created in a previous step.
server: httpServer,
// Pass a different path here if app.use
// serves expressMiddleware at a different path
// path: '/subscriptions',
});
const serverCleanup = useServer({ schema }, wsServer);
const server = new ApolloServer({
schema,
context: async ({req}) => {
let token = req.headers['token']
debugger; //<=== NEVER ACTIVATES
let userId = null;
try {
if (!!token) {
userId = await getUserIdByLoginToken(token)
}
} catch (error) {
console.log('context: ', error)
}
return {
userId: userId
};
},
plugins: [
// Proper shutdown for the HTTP server.
ApolloServerPluginDrainHttpServer({httpServer}),
// Proper shutdown for the WebSocket server.
{
async serverWillStart() {
return {
async drainServer() {
await serverCleanup.dispose();
},
};
},
},
],
});
await server.start();
app.use('/graphql', express.json(), expressMiddleware(server));
const PORT = 4000;
// Now that our HTTP server is fully set up, we can listen to it.
httpServer.listen(PORT, () => {
console.log(`Server is now running on http://localhost:${PORT}/graphql`);
});