GraphQL configuring Apollo server with Express Js

Hi in this post we are going to use our current Express Js configuration and add Apollo server.

Note: last GraphQL chapter was GraphQL get the UI project to start working

In your terminal go to /server folder then run:

npm i apollo-server-express graphql 

Then we are going to create the sever/schema.graphql file to save all our type definitions:

Note: we can use the .graphql extension in this file

type Query {
  greeting: String
}

The let’s create the server/resolvers.js file where lives all the query resolvers (the logic that are going to return the data):

const Query = {
  greeting: () => "Hellow LearnTechSystems",
};

module.exports = { Query };

Nice, next step is open the server.js file at this point we have some express js code, but lets add the apollo server configuration using the package apollo-server-express

we are going to need “fs” (file system) to use the schema.graphlfile in this section & ApolloServer to create a new server & also the gql that is going to help us to use the graphql language.

// Dependencies
const fs = require("fs"); // To load the .graphql file
const { ApolloServer, gql } = require("apollo-server-express");

.....

// GraphQL schema
const typeDefs = gql(
  fs.readFileSync("./schema.graphql", { encoding: "utf-8" })
);

// Resolver
const resolvers = require("./resolvers");

// Apollo server instance
const apolloServer = new ApolloServer({ typeDefs, resolvers });

// Plug apollo server into our existing Express aplication & set the // path http://localhost:9000/graphql
apolloServer.applyMiddleware({ app, path: "/graphql" });

Then open the terminal in /sever path and run:

npm start

Then open the browser and now we can run the query:

Here the entire server.js file:

// Dependencies
const fs = require("fs"); // To load the .graphql file
const { ApolloServer, gql } = require("apollo-server-express");

const bodyParser = require("body-parser");
const cors = require("cors");
const express = require("express");
const expressJwt = require("express-jwt");
const jwt = require("jsonwebtoken");
const db = require("./db");

const port = 9000;
const jwtSecret = Buffer.from("Zn8Q5tyZ/G1MHltc4F/gTkVJMlrbKiZt", "base64");

const app = express();
app.use(
  cors(),
  bodyParser.json(),
  expressJwt({
    secret: jwtSecret,
    credentialsRequired: false,
  })
);

// GraphQL schema
const typeDefs = gql(
  fs.readFileSync("./schema.graphql", { encoding: "utf-8" })
);

// Resolver
const resolvers = require("./resolvers");

// Apollo server instance
const apolloServer = new ApolloServer({ typeDefs, resolvers });

// Plug apollo server into our existing Express aplication
apolloServer.applyMiddleware({ app, path: "/graphql" });

app.post("/login", (req, res) => {
  const { email, password } = req.body;
  const user = db.users.list().find((user) => user.email === email);
  if (!(user && user.password === password)) {
    res.sendStatus(401);
    return;
  }
  const token = jwt.sign({ sub: user.id }, jwtSecret);
  res.send({ token });
});

app.listen(port, () => console.info(`Server started on port ${port}`));