Build Graphql folder structure and perform CRUD operations with JSON data #2
Hi there! So you want to gain a better understanding of graphql CRUD operations right! then you are at the right way, you just have to follow this tutorial, And if you are a beginner in graphql then please follow this tutorial, it will clear all the basic concepts. So, in this article, we’ll be focusing on graphql folder structure, and Perform Create, Update and Delete operations on JSON data.
Let’s Start
Step1: First we will create our project folders as follows
here we have created folders like DB, graphql, and server
Step 2:Run the following command to create the package.json file in your project folder.
npm init --yes
Step 3: Install the following dependencies
Step 4: Let’s create a server.js file inside the server folder
Step 5: Let's create typeDefs.js and resolvers.js file inside the graphql folder
Step 6: Let's create a database.js file inside DB folder
Paste the following JSON data there
const usersAr = [{id: 1,name: "gemmy",userEmail: "gemmy@123.com",age:22,nation: "INDIA"},{id: 2,name: "rone",userEmail: "rone@123.com",nation: "ENGLAND",age:22,friends:[{id: 4,name: "imma",userEmail: "imma@123.com",nation: "KATAR",age:30},]},{id: 3,name: "kat",userEmail: "kat@123.com",nation: "USA",age:25,friends:[{id: 4,name: "imma",userEmail: "imma@123.com",nation: "KATAR",age:30},]},{id: 4,name: "imma",userEmail: "imma@123.com",nation: "KATAR",age:30,friends:[{id: 1,name: "gemmy",userEmail: "gemmy@123.com",age:22,nation: "INDIA"}]},];const MoviresArr =[{id: 1,name: "Harry Potter",year:2001,theaters:true},{id: 2,name: "Matrix",year:2011,theaters:true},{id: 3,name: "YJHD",year:2008,theaters:false},]module.exports = {usersAr,MoviresArr};
Step 7: Now we will edit code in the typeDefs.js file
we have defined a basic model type related to our database
Step 8: Now go to type User and Movie paste the following code inside it.
type User {id: Int!name: String!userEmail: String!nation: Nation!age: Intfriends:[User]favMovies:[Movie]}type Movie{id:Int!name:String!year:Int!theaters:Boolean!}
here Nation is a predefined value type, it is ENUM. if you read more about it click here.
Step 9: Now we will go to Query type
type Query {getAllUsers: [User!]!getUserById(id:Int): User!getAllMovies:[Movie!]!}
I don't think I need to explain this, I hope you have followed my first article.
Step 10: Let's define our Mutation type
type Mutation {createUser(name: String!userEmail: String!nation: Nation = INDIAage: Int = 18): User!updateUserEmail(id: Int!, newupdateUserEmail: String!): UserdeleteUser(id: Int): User}
In our graphql schemas, we only have queries, it is all about returning existing data, there is nothing that modifies the data.
In GraphQL the operations that modify the data are called mutations. They must be kept separated from the queries. We need to add a separate type called Mutation. The mutation is a root type just like the query. Inside mutation, we can find operations like create, update, and delete.
Mutations allow clients to manipulate data (i.e., create, update, or delete, similar to POST, PUT, or DELETE, respectively).
here we have a mutation for creating a new user as [createUser], for that we need to pass the arguments for adding the user. If you look at User type you have
name: String!userEmail: String!nation: Nation = INDIAage: Int = 18
these fields are known as Arguments in Mutation.
here you can see nation and age are predefined suppose we did not enter any value then it will consider its predefine value.
This ‘!’ mark means this particular field should not be empty.
Step 11: Let's define our ENUM
we will define enum after mutation type
enum Nation{INDIAENGLANDUSAKATAR}
Step 12: Now onwards we will do changes in the resolver.js file
we will be importing the database.js file in resolvers.js
const {usersAr,MoviresArr}= require('../DB/database');
here we have defined a basic model structure for resolvers
the basic definition of resolvers I can say that it has a logic to handle defined Queries and Mutations.
Step 13: So let's resolve our query First
Here, getAllUsers returning us All the list of userAr, same goes for getAllMovies
In getUserById we are receiving an argument from the client and it will be matched with database userAr id and finally, it will be returned to function
Step 14: Now we will resolve our Mutations
Now we are ready to create a mutation function for creating a User.
explanation: whatever arguments I am passing from graphqlPlayground it will be stored into user variable, to add our data consistently we need to find the last Id of an existing array after that, we can assign value to the user. id with the help of the last id
finally, data is pushed to that particular array.
we have written the resolver to update the Email according to its Id, code is simple to understand.
We will see the delete operation in the next article where we connected with the database
Step 15: Now we will configer our server,js file
const { ApolloServer } = require("apollo-server");const {typeDefs} =require('../graphql/typeDefs');const {resolvers} =require('../graphql/resolvers');const server = new ApolloServer({ typeDefs, resolvers });server.listen().then(({ url }) => {console.log(`App is running At : ${url}`);});
this way we have to build the server.js file
Step 16: Now we will run our project.
you can see the default value is being inserted into the database. And the email is getting updated.
Wrapping Up
In this article, We have performed crud operations like insert update
We also understand typeDefs, Query, resolvers.