Home > front end >  How to setup graphql subscriptions on apollo server express?
How to setup graphql subscriptions on apollo server express?

Time:02-17

I am not finding any solutions. I already asked one questions about this. But not finding solutions. I already created a graphql projects with apollo-server-express.

I create three file apollo.js, app.js and server.js.

In app.js I write-

const express = require("express");
const cors = require("cors");
//App
const app = express();

app.use(express.json({limit: '50mb'}))
app.use(cors());

module.exports = app;

In apollo.js-

// Packages
const {ApolloServer} = require("apollo-server-express");
const Dataloader = require("dataloader");
//TypeDefs & Resolvers
const typeDefs = require("./TypeDefs/main");
const resolvers = require("./Resolvers/main");
//Authorizations
const {Token} = require("./Authorizations/Token");
//Loaders
const loaders = require("./Loaders/main");


const apolloServer = new ApolloServer({
    typeDefs,
    resolvers,
    context: async ({req, connection}) => {
        await Token(req);
        return {
            reqUserInfo: req.user
        }
    },
});

module.exports = apolloServer;

In the last I create the express server in server.js

//Packages
require("dotenv/config");
const mongoose = require("mongoose");
const {graphqlUploadExpress} = require("graphql-upload");

//App & ApolloServer
const app = require("./app");
const apolloServer = require("./apollo");

async function startServer() {
    app.use(graphqlUploadExpress())
    await apolloServer.start();
    apolloServer.applyMiddleware({app, path: '/graphql'});
    app.use("/", (req, res) => {
        res.send("Welcome to tradewatch platform")
    })
}

//StartServer
startServer();
mongoose.connect(process.env.MONGODB_LOCAL_URL)
    .then(() => console.log("MongoDB Connected Successfully!"))
    .catch((err) => console.log("MognoDB Connetion Failed!"));
//Server Creations
const port = process.env.PORT || 3001;
const httpServer = app.listen(port, () => {
    console.log(`App is running on port ${port}`);
    console.log(`GraphQl EndPoint path: /graphql`);
});

Now I want to add graphql subscriptions in this project. How can I add this. I already install subscriptions-transport-ws and @graphql-tools/schema. Please say if I need more package to install.

**** My question is, what things should I change in this 3 files. Please help me.

CodePudding user response:

Nothing heavy, you have to change only few things. As you want to add graphql-subscription then you need to install it also beside subscriptions-transport-ws and @graphql-tools/schema that you already installed. Just install one more that is graphql-subscriptions.

npm i graphql-subscriptions

In app.js you not need to change anythings.

In apollo.js-

// Packages
const {ApolloServer} = require("apollo-server-express");
const Dataloader = require("dataloader");
// Added Newly
const {makeExecutableSchema} = require("@graphql-tools/schema");
//TypeDefs & Resolvers
const typeDefs = require("./TypeDefs/main");
const resolvers = require("./Resolvers/main");
//Authorizations
const {Token} = require("./Authorizations/Token");
//Loaders
const loaders = require("./Loaders/main");

// Add Executeable Schema
const schema = makeExecutableSchema({typeDefs, resolvers});


const apolloServer = new ApolloServer({
    schema, // Remove TypeDefs and Resolvers and add schema
    context: async ({req}) => { // Remove connection
        await Token(req);
        return {
            reqUserInfo: req.user
        }
    },
});

module.exports.apolloServer = apolloServer;
module.exports.Schema = schema

Then i server.js -

//Packages
require("dotenv/config");
const mongoose = require("mongoose");
const {graphqlUploadExpress} = require("graphql-upload");
//Add new Packages
const {createServer} = require("http"); // For creating server
const {subscribe, execute} = require("graphql");
const {SubscriptionServer} = require("subscriptions-transport-ws");

//App & ApolloServer
const app = require("./app");
const {apolloServer, Schema} = require("./apollo"); // Import Schema as well

async function startServer() {
    app.use(graphqlUploadExpress())
    await apolloServer.start();
    apolloServer.applyMiddleware({app, path: '/graphql'});
    app.use("/", (req, res) => {
        res.send("Welcome to tradewatch platform")
    })
}

//StartServer
startServer();
mongoose.connect(process.env.MONGODB_LOCAL_URL)
    .then(() => console.log("MongoDB Connected Successfully!"))
    .catch((err) => console.log("MognoDB Connetion Failed!"));
//Server Creations
const port = process.env.PORT || 3001;
const server = createServer(app);
server.listen(port, () => {
    new SubscriptionServer({
        execute,
        subscribe,
        schema: Schema,
    }, {
        server: server,
        path: '/tradewatch',
    });
    console.log(`App is running on port ${port}`);
    console.log(`GraphQl EndPoint path: /graphql`);
});

That's it. Thank you very much.

  • Related