Create GraphQl API with Apollo Server, Node and MongoDb

Author
April 06, 2022

In this article i will explain you step by step to setup GraphQL API with Apollo Server, Node and MongoDb Step By Step

Step 1: Initial project setup and installing dependencies

Run below command to initialize project with default settings

npm init -y

Run below command to install mongoose, graphql and apollo-server

npm install mongoose graphql apollo-server

Run below command to install nodemon as a dev dependencies

npm install --save-dev nodemon

Step 2: Create GraphQl Schema and Resolvers

We will be creating rest api to save, update, delete notes for that we need to define graphql schema which define type of post and get query we will be executing and resolvers which act as controller and we will be writing logic here to interact with our mongodb database

Create a folder name graphql under root path of your project under that folder create two js file with the name resolvers.js and schema.js

Update the schema.js file with the following code

const { gql } = require("apollo-server");

//GraphQL Schemas
module.exports = gql`
  type Note {
    _id: ID!
    title: String!
    content: String!
    createdAt: String!
    updatedAt: String!
  }

  input NoteInputData {
    title: String!
    content: String!
  }

  type Query {
    getNotes: [Note!]!
    getNote(id: ID!): Note!
  }

  input NoteInputData {
    title: String!
    content: String!
  }

  type Mutation {
    createNote(noteInput: NoteInputData): Note!
    updateNote(id: ID!, noteInput: NoteInputData): Note!
    deleteNote(id: ID!): Boolean
  }
`;

Update the resolvers.js file with the following code

const Note = require("../models/note");

module.exports = {
  Query: {
    getNote: async (parent, args) => {
      try {
        const { id } = args;
        const note = await Note.findById(id);
        if (!note) {
          const error = new Error("No note found!");
          error.code = 404;
          throw error;
        }
        return note;
      } catch (error) {
        throw new Error(error);
      }
    },
    getNotes: async (parent, args) => {
      try {
        const notes = await Note.find();
        return notes;
      } catch (error) {
        throw new Error(error);
      }
    },
  },

  Mutation: {
    createNote: async (parent, args) => {
      try {
        const { noteInput } = args;
        return await Note.create(noteInput);
      } catch (error) {
        throw new Error(error);
      }
    },
    updateNote: async (parent, args) => {
      try {
        const { id, noteInput } = args;
        const note = await Note.findById(id);
        if (!note) {
          const error = new Error("No note found!");
          error.code = 404;
          throw error;
        }
        return await Note.findOneAndUpdate(id, noteInput, { new: true });
      } catch (error) {
        throw new Error(error);
      }
    },
    deleteNote: async (parent, args) => {
      try {
        const { id } = args;
        const note = await Note.findById(id);
        if (!note) {
          const error = new Error("No post found!");
          error.code = 404;
          throw error;
        }
        await Note.findByIdAndDelete(id);
        return true;
      } catch (error) {
        throw new Error(error);
      }
    },
  },
};

Step 3: Create mongoose schema model

Create a folder name models under root path of your project and create note.js file under that folder

Update note.js file with following code

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const noteSchema = new Schema(
  {
    title: {
      type: String,
      required: true,
    },
    content: {
      type: String,
      required: true,
    },
  },
  { timestamps: true }
);

module.exports = mongoose.model("Note", noteSchema);

Step 4: Create app.js file under root path of your project

File app.js is the main file to start Apollo server and connect to mongodb database

Update your app.js file with the following code

const { ApolloServer } = require("apollo-server");
const graphqlSchema = require("./graphql/schema");
const graphqlResolver = require("./graphql/resolvers");
const mongoose = require("mongoose");

mongoose
  .connect("mongodb://localhost:27017/notes", {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => {
    console.log("Connected to database");
  })
  .catch((error) => {
    throw new Error(error);
  });

const server = new ApolloServer({
  typeDefs: graphqlSchema,
  resolvers: graphqlResolver,
});

//Starting apollor server
server.listen().then(({ url }) => {
  console.log(`Server listening at ${url}`);
});

Step 5: Run the app and test the api

Update your package.json file and add start script and update nodemon to start your app.js file which is the main file to start the server

    "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon app.js"
  },

Go to your terminal and go to your folder path and run below command to start the apollo server

npm start

typescript-install

Go to http://localhost:4000/graphql and start querying your rest api

typescript-install

typescript-install