DEV Community

loading...
Cover image for My own realtime chat with react, graphql and postgresql [part 4 - Server]

My own realtime chat with react, graphql and postgresql [part 4 - Server]

dalejan profile image David Alejandro Quiñonez ・2 min read

So, previously we've already created our queries, mutations, and subscriptions in order to login and chat in our application.
But now we have to serve our backend so any frontend can consume it.

To do this we've to create the index.js file.

./index.js

const { typeDefs, resolvers } = require("./graphql/index");
const { ApolloServer } = require("apollo-server-express");
const { createServer } = require("http");

const app = require("express")();
const PORT = process.env.PORT || 8080;

const server = new ApolloServer({
  typeDefs,
  resolvers,
  subscriptions: {
    onConnect: () => {
      console.log("coneected");
    },
    onDisconnect: () => {
      console.log("disconected");
    },
  },
});


// Initialize the app
server.applyMiddleware({ app });

const httpServer = createServer(app);
server.installSubscriptionHandlers(httpServer);

// Wrap the Express server
httpServer.listen(PORT, () => {
  console.log(`🚀 Server readys at http://localhost:${PORT}/graphql`);
  console.log(`🚀 Subscriptions ready at ws://localhost:${PORT}/graphql`);
});

Enter fullscreen mode Exit fullscreen mode

As usual, lets break it down.

  1. The ApolloServer is basically an object that group the schemas, the functions and the socket subscriptions to serve them online.
  2. On that apolloServer we now apply an express server as a middleware. Then we use the subscription handlers from apollo in order to allow the socket connection.
  3. Finally we serve the server at a specific port, with the listen function.

Now we can add a run script in our package.json

./package.json

...
"scripts": {
  "start": "index",
   ...
},
...
Enter fullscreen mode Exit fullscreen mode

Or use 'nodemon index' instead, if you want a livereload of your changes.

Lets run it! (npm start).

In our browser we can now access to the server (The full path is printed on the server console once you run the script).

And voila!

Alt Text

In the next part we will be using this interface to build the queries and mutations and check if everything was setted up correctly.

Discussion

pic
Editor guide