I'm encountering an issue with setting up subscriptions in my Apollo Server project using Express. Despite following all the steps outlined in the documentation [https://typegraphql.com/docs/subscriptions.html], I can't seem to get it working. Initially, I couldn't even listen for subscriptions, so I wrapped my Express app with an HTTP server and added a new subscription server within my app.listen function to enable listening. However, now when I try to trigger a subscription with a mutation, it doesn't work at all. I've tried various solutions found on Stack Overflow and GitHub without any success.
Below is a snippet of the server code:
import express from "express";
import { ApolloServer } from "apollo-server-express";
import cors from "cors";
import { SubscriptionServer } from "subscriptions-transport-ws";
import { execute, subscribe } from "graphql";
import { createServer } from "http";
const main = () => {
const app = express();
app.use(
cors({
origin: "http://localhost:3000",
credentials: true,
})
);
const apolloServer = new ApolloServer({
playground: {
settings: {
"request.credentials": "include",
},
},
schema: await buildSchema({
resolvers: [Resolver1, Resolver2, Resolver3],
validate: false,
}),
context: ({ req, res }) => ({ req, res, redis }),
});
apolloServer.applyMiddleware({
app,
cors: false,
});
const server = createServer(app);
server.listen(4000, async () => {
console.log("Server running on port 4000");
new SubscriptionServer(
{
execute,
subscribe,
schema: await buildSchema({
resolvers: [Resolver1, Resolver2, Resolver3],
validate: false,
}),
},
{
server,
path: "/graphql",
}
);
});
};
If you notice any mistakes in my approach or can provide guidance on what I might be missing, please assist me in the right direction.