"""===========================================================
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
install apollo client
install graphQL
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.