How to GraphQl | When to GraphQl - GraphQl MongoDB NodeJs Integration

graphql mongodb



For a light introduction, I would say, the main application of GraphQL api is as an API (Application Programming Interface) query language. GraphQL apollo gives clients a more effective and customizable way to query, add, and update data stored on a server. 

What GraphQL is Used for?

We have our rest apis, but why GraphQL  is used then? Can GraphQL replace rest? No, it won't. But as per graphql documentationGraphQL  query offers some best to have features that we should not ignore. 

Graphql Query Schema

In a GraphQL server, the GraphQL schema is the structure and specification of the data users can request from a GraphQL fastapi. It is a key aspect of GraphQL that establishes a clear commitment between the client and the server regarding the accessible data and how it can be accessed.

GraphQL Schema Example

   
    type Query {
      book(id: ID!): Book
      author(id: ID!): Author
      books: [Book]
      authors: [Author]
    }

    type Mutation {
      addBook(title: String!, authorId: ID!): Book
    }

    type Subscription {
      bookAdded: Book
    }

    type Book {
      id: ID!
      title: String!
      author: Author!
    }

    type Author {
      id: ID!
      name: String!
      books: [Book]
    }


Ask for Exactly What you Need

GraphQL queries guarantee that you receive only the data you look for, with no unnecessary information. This consistency leads to speedier and more stable applications since clients have control over the data they get, rather than the server controlling its structure.

GraphQL example query

 
  query {
    books {
      id
      title
      author {
        id
        name
      }
    }
  }


GraphQL vs Rest | Single Request - Many Resources

If we compare graphql and rest - which need several endpoint requests, GraphQL queries quickly develop connections between resources. GraphQL allows you to get all of your application's data in a single request.

GraphQL and MongoDB - Let's Connect them

GraphQL with MongoDB is a powerful combination to develop highly scalable APIs. This will be graphql 101 setup with nodejs mongodb.

Set up Project

 We will create a new project for graphql nodejs with mongodb. 

 
  mkdir graphql-mongodb-nodejs
  cd graphql-mongodb-nodejs
  npm init -y


Install some Dependencies

You'll need packages to create a GraphQL request with MongoDB integration:

 
  npm install express graphql express-graphql mongoose


GraphQL MongoDB Set up

Make sure MongoDB is installed locally or use a cloud-based MongoDB service - MongoDB Atlas.

Create MongoDB Schema

Create a models directory and design your MongoDB schema with Mongoose. For example, create models/Book.js.

 
 const mongoose = require('mongoose');

  const bookSchema = new mongoose.Schema({
    title: String,
    author: String,
  });

  module.exports = mongoose.model('Book', bookSchema);


Create GraphQL Schema

Create your GraphQL schema using the GraphQL SDL (Schema Definition Language).
 
 
  const { buildSchema } = require('graphql');

  const schema = buildSchema(`
    type Book {
      id: ID!
      title: String!
      author: String!
    }

    type Query {
      books: [Book]
      book(id: ID!): Book
    }

    type Mutation {
      addBook(title: String!, author: String!): Book
    }
  `);

  module.exports = schema;


Add GraphQL Resolver

Resolvers are functions that perform the GraphQL operations specified in the schema. Create a new file named graphql /Resolvers.js and add the following code.

 
const Book = require('../models/Book');

  const resolvers = {
    Query: {
      books: async () => {
        try {
          return await Book.find();
        } catch (err) {
          throw new Error('Failed to fetch books');
        }
      },
      book: async ({ id }) => {
        try {
          return await Book.findById(id);
        } catch (err) {
          throw new Error('Failed to fetch book');
        }
      },
    },
    Mutation: {
      addBook: async ({ title, author }) => {
        try {
          const book = new Book({ title, author });
          await book.save();
          return book;
        } catch (err) {
          throw new Error('Failed to add book');
        }
      },
    },
  };

  module.exports = resolvers;


Create Express GraphQL Server

Set up an GraphQL express server and setup it to use GraphQL and MongoDB. Create server.js.

 
  const express = require('express');
  const mongoose = require('mongoose');
  const graphqlHTTP = require('express-graphql');
  const schema = require('./schema/schema');
  const resolvers = require('./resolvers/book');

  const app = express();

  const mongoURI = 'mongodb://localhost:27017/graphql-demo';
  mongoose.connect(mongoURI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  });
  mongoose.connection.once('open', () => {
    console.log('Connected to MongoDB');
  });

  app.use('/graphql', graphqlHTTP({
    schema,
    rootValue: resolvers,
    graphiql: true,
  }));

  app.listen(4000, () => {
    console.log('Server running at http://localhost:4000/graphql');
  });


Start the Server

Run node index.js

 
  node server.js

Well done! You've created a GraphQL request API that uses Node.js and MongoDB to smoothly manage data operations. This graphql database allows you to easily manage data creation, retrieval, updates, and deletion. Ensure that graphql errors handling is effective, and further customize the API to match the individual project requirements.

Happy Coding✌

Frequently Asked Questions

Which database is best for GraphQL?

It depends on your requirement. Through I will prefer GraphQL with:

  • MongoDB
  • PostgreSQL
  • mySQL

Which is better GraphQL or rest?

The choice between GraphQL vs REST is mostly determined by your project's individual requirements and features. 

Which database support GraphQL?

GraphQL Native Databases

     -Hasura

     -Prisma

     -FaunaDB

GraphQL Wrappers

     -Apollo Server

     -AWS AppSync

Custom GraphQL APIs

     -GraphQL Yoga

     -GraphQL Tools

How to use GraphQL where clause?

 
  type Query {
    users(filter: UserFilterInput): [User]
  }


How GraphQL query use?

 
  type Query {
    hello: String
    getUser(id: ID!): User
  }

  type User {
    id: ID!
    name: String!
    email: String!
  }


Can GraphQL call rest api?

Yes, GraphQL can call rest apis. 

 
  const { ApolloServer, gql } = require('apollo-server');
  const axios = require('axios');

  const typeDefs = gql`
    type Book {
      id: ID!
      title: String!
      author: String!
      publishedYear: Int!
    }

    type Query {
      books: [Book]
    }
  `;

  const resolvers = {
    Query: {
      books: async () => {
        try {
          const response = await axios.get('https://api.example.com/books');
          return response.data; // Assuming the API returns an array of books
        } catch (error) {
          throw new Error('Failed to fetch books from the REST API');
        }
      },
    },
  };

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

  server.listen().then(({ url }) => {
    console.log(`Server ready at ${url}`);
  });


What are GraphQL resolvers?

GraphQL resolvers are functions that get data for a GraphQL query and populate the values of the fields in the query's response. Resolvers are a key part of any GraphQL server since they control how data is fetched and converted based on the client's request.

Can GraphQL be used with mySQL?

Yes, GraphQL can be used with MySQL.


codegirl

Hello, I’m Sangita, person behind "codegirl", a dedicated web developer. Crafting digital experiences is not just my job; it’s my passion. Let’s build something exceptional together!

Post a Comment

Previous Post Next Post