Hello,
Im trying to implement ws with http, I followed the guide in the docs,
import { createServer } from "http";
import { execute, subscribe } from "graphql";
import { SubscriptionServer } from "subscriptions-transport-ws";
import { makeExecutableSchema } from "@graphql-tools/schema";
import express from "express";
import { ApolloServer } from "apollo-server-express";
import resolvers from "./resolvers";
import typeDefs from "./typeDefs";
(async function () {
const app = express();
const httpServer = createServer(app);
const schema = makeExecutableSchema({
typeDefs,
resolvers,
});
const subscriptionServer = SubscriptionServer.create(
{
schema,
execute,
subscribe,
async onConnect(connectionParams) {
if (connectionParams.authorization) {
const currentUser = await findUser(connectionParams.authorization);
return { currentUser };
}
throw new Error('Missing auth token!');
}
},
{ server: httpServer, path: server.graphqlPath }
);
const server = new ApolloServer({
schema,
plugins: [{
async serverWillStart() {
return {
async drainServer() {
subscriptionServer.close();
}
};
}
}],
});
await server.start();
server.applyMiddleware({ app });
const PORT = 4000;
httpServer.listen(PORT, () =>
console.log(`Server is now running on http://localhost:${PORT}/graphql`)
);
})();
Now, i implemented the context for ws with the onConnect function, but how do i implemnt it for the http requests? usually i create a context like this:
const context ({req}) => {
// authentication
return {user: 'some-user'};
}
and i pass that function to the ApolloServer instance, but if i try to pass it now with all the ws aditions,
and i make like 2 requests, it starts an infinite loop in the context and executing the context function non stop.
Am i doing something wrong? I can’t figure it out, was also searching in the web for hours and nothing.
Would love to get some help on this issue.
Thanks a lot!