Build A Library Application With Graphql ExpressJs React-Apollo and MongoDB (Part 5)

in #utopian-io5 years ago

graphql.fw.png

Repository

React

https://github.com/facebook/react

Graphql

https://github.com/graphql/graphql-js

Apollo

https://github.com/apollographql/apollo-client

Express

https://github.com/expressjs/express

My Github Address

https://github.com/pckurdu

This Project Github Address

https://github.com/pckurdu/Build-A-Library-Application-With-Graphql-ExpressJs-React-Apollo-and-MongoDB-Part-5

What Will I Learn?

  • You will learn how to add data to the mLab database with graphql mutation.
  • You will learn how to control data when inserting data with Graphql.
  • You will learn how to get data from the mLab database with Graphql.
  • You will learn the type and usage of GraphQLNonNull.
  • You will learn the functions findById() and find() in mLab.

Requirements

  • text editor (I used visual studio code editor)
  • Basic javascript information
  • Basic react information

Difficulty

  • Basic

Tutorial Contents

Hello to everyone,

In this tutorial, we will continue the mutation process and perform book insertion. When adding the book, we will use the id information of the authors previously added to the database so that we link the books and the authors.

Then we'll edit the fields we've created in rootQuery to get the books and authors from the database. We will be able to access the data in mLab with GraphiQL as a result of this editing process.

Then we will examine the GraphQLNonNull type. Thanks to the GraphQLNonNull type, we will be able to check the data passed during the insertion process. We will learn the structure and usage of GraphQLNonNull type.

The titles of the sections of this tutorial are listed below:

  • Adding Books With Mutation
  • Update Resolve Functions
  • Using Graphql NonNull

Let’s start.

1- Adding Books With Mutation

In this section, we will perform book insertion operations using mutation. In the previous tutorial we created the mutation field. In this section, all we have to do is create a add book field in the previously created mutation field and we will add books in this field.

In Mutation

//adding book field
addBook:{

}



We need to create the required args and resolve() for mutation.

In the args field, we will define the properties of the book and use these properties to add the book in the resolve () function.

//adding book field
addBook:{
//author add operations
   type:bookType,
   args:{
      name:{type:GraphQLString},
      type:{type:GraphQLString},
      authorId:{type:GraphQLID}
   },
   resolve(parent,args){
     //mongoDB codes
     let book=new Book({
        name:args.name,
        type:args.type,
        authorId:args.authorId
  });
  //we are saving the book
  return book.save();
  }
}



We can now add books using mutation. Let's add our first book.

We can observe the addBook mutation in the GraphiQL domain.
graphql1.gif


To add books, we need authorId information. We added authors to the authors collection in mLab, which automatically generated Id information. We can add the book by getting the ID of this author.

graphql2.gif


We can now add books from GraphiQL.
graphql3.gif


There is now a books document in the database, and we have brought the authorId from the Id.

graphql4.gif


So we can add books and authors using graphql.

2- Update Resolve Functions

Now that we have added book and author information to the database, we can get this information. In this section, we will perform the editing of the previously defined resolve functions to fetch the data.

First we will edit the resolve function in bookType.

resolve(parent,args){              
 //Calling the author in bookType
 return Author.findById(parent.authorId);
}



In bookType, we used the findById () function to retrieve the author's information from the database.

To bring up a book with which we know its id, we need to edit the book field in RootQuery. We used the parent parameter to access the author's information in bookType, but in the book field we will use the args parameter to access the properties of the book.

In RootQuery

book:{
  type:bookType,
  args:{id:{type:GraphQLID}},
  resolve(parent,args){
  //Data coming from database
  // book get
  return Book.findById(args.id);
  }
},



So we can now access the book information in the database.

graphql5.gif


To show an author whose id we know, we need to edit the resolve () functions in the author fields in authorType and RootQuery. Edit the resolve () function in authorType.

resolve(parent,args){
  //Calling the author in bookType
  return Book.find({authorId:parent.id});
}



Here we edit the book information in authorType so we can access lists of the author's books.

We can show the author's information by editing the author field in RootQuery.

In RootQuery

//first type for author use authorType
author:{
   type:authorType,
   args:{id:{type:GraphQLID}},
   resolve(parent,args){
      //Data coming from database
      //get author
      return Author.findById(args.id);
   }
},



Let's access the information of the author whose id is in the database.
graphql6.gif


Since we have reached the information of the author and the book whose id we know, we can also write the codes to list all the books and authors. We can do this by editing the books and authors fields in RootQuery.

//for book list
books:{
   type:new GraphQLList(bookType),
   resolve(parent,args){
     // return books
     return Book.find({});
  }
},
//for author list
authors:{
   type:new GraphQLList(authorType),
   resolve(parent,args){
     //return authors
     return Author.find({});
    }
}



We used the find() function to fetch all authors and books and left it empty. mongoDB has set such a syntax when fetching all data. If we do not make a fetch according to a criterion, we must leave it blank.

Let us show the process of listing books and authors in GraphiQL.

For books list

graphql7.gif


For authors list.

graphql8.gif

3- Using Graphql NonNull

In this section we'll use Graphql NonNull and talk about what it does.

We can now add book and author information to the database we created on mLab but we can add data as incomplete because we perform the insertion operations without any limitation. For example, if we do not give the type of the book during the book insertion process, the type field of that data is created, but it is inserted blank. This is a problem that needs to be solved because it will cause us to save the data incorrectly.

With the Graphql NonNull type, we can prevent null passing of data fields. Blank relay is prevented by using the NonNull parameter when creating data fields.

To use the GraphQLNonNull type, we must first define it.

//for book type and book fields
const {…,GraphQLNonNull}=graphql;



Since data insertion is performed in the mutation field, we should use NonNull here so that data cannot be empty at the time of insertion. Where we define arguments in the addBook and addAuthor fields, we should use GraphQLNonNull.

addAuthor:{
  //author add operations
  type:authorType,
  args:{
      //define GraphQLNonNull
      name:{type:new GraphQLNonNull(GraphQLString)},
      age:{type:new GraphQLNonNull(GraphQLInt)}
  },
  resolve(parent,args){
       //mongoDB codes
    },
        //adding book field
  addBook:{
      //author add operations
      type:bookType,
      args:{
         //define GraphQLNonNull
         name:{type:new GraphQLNonNull(GraphQLString)},
         type:{type:new GraphQLNonNull(GraphQLString)},
         authorId:{type:new GraphQLNonNull(GraphQLID)}
    },
    resolve(parent,args){
                 //mongoDB codes
     }
}



The parameter cannot be passed as empty during book insertion and author insertion.
graphql9.gif


See you next tutorial.

Curriculum

Part 1 - Part 2 - Part 3 - Part 4

Proof of Work Done

https://github.com/pckurdu/Build-A-Library-Application-With-Graphql-ExpressJs-React-Apollo-and-MongoDB-Part-5

Sort:  

Thank you for your contribution @pckurdu.
After reviewing your tutorial we suggest the following points listed below:

  • Again an excellent tutorial, well structured and well explained. Keep up the good work!

  • Thanks for following our suggestions we gave in previous tutorials.

Looking forward to your upcoming tutorials.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Chat with us on Discord.

[utopian-moderator]

Thank you for your review, @portugalcoin! Keep up the good work!

Hi @pckurdu!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server

Hey, @pckurdu!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Coin Marketplace

STEEM 0.27
TRX 0.13
JST 0.032
BTC 62656.62
ETH 2941.90
USDT 1.00
SBD 3.59