Skip to main content

Command Palette

Search for a command to run...

graph QL

Updated
3 min readView as Markdown
graph QL
R

FRONT-END WEB DEVELOPER

"""===========================================================
         goto to https://countries.trevorblades.com/
=============================================================="""
type User{
  id:ID
  name:String
  age:Int
  height:Float
  isMarried:Boolean! """ ======"""
  firends:[User] """======"""
  videosPosted: [Video]
}

type Video {
  id:ID!
  title:String!
  description:String!
}




"""========= """
type Query{
users:[User]
user(id:ID):User 
user(id:ID, name:String ):User
}


"""============query from api ========="""
{
  country(code:"US"){
    code
    name
    capital
    currencies
    phone
    continent{
countries{capital}
      name
    }
  }
}

start graph ql with node js application

npm init -y
npm install apollo-server graphql nodemon
"""create a app file or index.js file"""
""" create a schema folder """
""" insha allahide schema folder create 3 file. 
1. resolvers.js
2. typeDefs.js
3. fakeData.js ==> because we aren't use any database
 """

index.js

const { ApolloServer } = require("apollo-server");
const typeDefs = require("./schema/typeDefs");
const { resolvers } = require("./schema/resolvers");

const server = new ApolloServer({ typeDefs, resolvers });
server
 .listen()
 .then(({ url }) => {
  console.log(`API IS RUNNING ON ${url}`);
 })
 .catch((err) => console.log(err));

typeDefs.js

// get all users 
// get single user
// enum types
const { gql } = require("apollo-server");
const typeDefs = gql`
 type User {
  id: ID!
  name: String!
  userName: String!
  age: Int!
  nationality: Nationality!
  friends: [User]
 }
 type Query {
  users: [User!]!
  user(id: ID!): User!
 }

 enum Nationality { 
  BD
  INDIA
 }
`;
module.exports = typeDefs;

resolvers.js

const { userList } = require("../schema/fakeData");

const resolvers = {
 Query: {
  users() { // all user api
   return userList;
  },
  user(_parent, args) { // single user api
   const user = userList.find((user) => user.id === Number(args.id));
   return user;
  },
 },
};
module.exports = { resolvers };

এই কাজ গুলো করলে আমাদের apollo server রান করার কাজ শেষ হয়ে যাবে । এখন আপনি আপনার ডাটা অ্যাক্সেস করতে পারবেন ড্যাশবোর্ড থেকে । ঠিক এইভাবে

নিয়ম ১ ঃ

নিয়ম ২ ঃ

Mutation

create :

resolvers.js

Mutation: {
  createUser: (parent, args) => {
   const user = args.input;
   userList.push(user);
   return user;
  },
  // update user
  updateUser: (parent, args) => {
   const { id, userName } = args.input;
   const findedUser = userList.find(
    (user) => parseInt(user.id) === parseInt(id)
   );
   findedUser.userName = userName;
   return findedUser;
  },

 },

typeDefs.js


 input CreateUserInput {
  id: ID!
  name: String!
  userName: String!
  age: Int!
  nationality: Nationality!
 }
 input UpdateInput {
  userName: String!
  id: ID!
 }
 type Mutation {
  createUser(input: CreateUserInput!): User!
  updateUser(input: UpdateInput!): User!
 }

this is the process

start graphql on react

  1. install apollo client

  2. install graphQL

  3. npm install @apollo/client graphql
    install command

on react component অথবা যেখানে ইহা কনফিগার করতে চান সেখানে ।

//============= import some package or enything ===============
const { ApolloClient ,InMamoryCache, ApploProvider, useQuery, gql, useLazyQuery} from "@apollo/client"

// ========== this configuration for userQuery hooks==========
const QUERY_ALL_USERS = gql`
    query getAlluser{
      users {
        age
        name
        userName
      }
    }
`
const QUERY_SINGLE_USER = gql`
    query getSingleUser($userId: ID!){
      user(id: $userId) {
       name
       userName 
      }
    }
`
// app component
const App = () =>{
// =========== configuration for graphQL =============
const client = new ApolloClient({
    cache: new InMamoryCache(), 
    uri: "http://localhost:4000/graphql", 
}),
//============== calling api [query] ===================
const { data, loading, error, refetch } = useQuery(QUERY_ALL_USERS)
                             // 👆👆 to fetch data again 

// single user [query] with passing arguemtns [userId]
const [ getSingleUser, {data, loading, error} ]= useLazyQuery(QUERY_SINGLE_USER)

    // ----------if you want to do user can click on the button for   refech api. how can we do that     

const [fatchusers, {data, error}] = useLazyQuery(QUERY_ALL_USERS)
     // 👆👆👆👆👆 it's fetcher function

// ============= calling api [Mutation] ================

    //========================================================
    //                   ======render JSX=====
    //========================================================
return <ApploProvider client={client}>
   <h1>Explore graphQl on React JS</h1>
   <div>
   {
    data
    .users
    .map((user,index) => <div key={index}>{user.name}</div>)
   }
   </div>

<button onClick={() => getSingleUser({ variables:{ userId:1 }})}>get Single user by passing arguemnts</button>

   <button onClick={fatchusers} > Refresh users </button>
</ApploProvider>
}

now ready to work this react application with graphQL api.

same method to update, create and delete Just useMutation will replace useQuery.

More from this blog

Learning MySQL Database for beginners (Bangla)

today I will discuss about Database. this article can be read by all types o people, don't worry. আপনাদের প্রথমে ডাটাবেস নিয়ে পড়াশুনা করতে আসলে মনে হতে পারে এই ডাটাবেস আবার কি ? ডাটাবেস হল data + base এঁর সমন্বয়ে গঠিত একটি শব্দ । যার বাংলা অর্থ হচ্ছে...

May 24, 202317 min read85
Learning  MySQL Database for beginners  (Bangla)

simple discussion about mono repo

আমরা যখন একজন full-stack web developer তখন আমাদের backend and front-end সম্পর্কে বেশ ভালো জ্ঞান থাকতে হয় । অনেক সময় আমাদের একজকেই একটা প্রোজেক্ট এঁর backend and front-end এঁর কোড ম্যানেজ করতে হয় । বাক্তি ভেদে বিভিন্ন জন বিভিন্নভাবে প্রোজেক্টর backend...

Apr 13, 20232 min read15
simple discussion about mono repo

node js basic shorts (syntax and pattern)

এই প্রবন্ধে আমরা জানার চেষ্টা করব কে node JS এঁর কিছু কমন সিনট্যাক্স এন্ড প্যাটার্ন , যা আমরা প্রতিনিয়ত ভুলে যাই । কিভাবে নোড জেএস এ সার্ভার তৈরি করতে হয় ? const http = require("http"); const server = http.createServer((req, res) => { res.statusCode...

Apr 2, 20232 min read15
node js basic shorts (syntax and pattern)
M

MD. Rashedul Islam shihab

15 posts

Official blog of MD. Rashedul Islam Shihab, sharing practical programming tutorials, software development insights, project experiences, and the latest web technologies.