May 08, 2021
| Content |
|---|
| GraphQL |
| Callstack & tasks queue |
| JS runtime and web APIs |
Any application needing to make HTTP calls between a client and a server to send and receive data, it uses a REST API. Let's say we have build a web application with a few different clients:
- A web application for users to login and manage their data
- A mobile application for IOS users to manage their data on the go.
Unlike REST APIs, a GQL API is going to have just single endpoint exposed, that's called Query (as Query from GraphQL Query playground)
GraphQL here
------------
query {
user {
id, ------> I'm able to query 2 different objects and not necessarily
pick every prop in the object either..
name
city
}
product {
pid ------> In mobile, I could fetch just the bare minimum to make sure
title load time remains uncompromised.
In desktop, I could go all in, and grab other relevant
price data associated with this object such as comments, and or
etc.. product ratings.
}
}
_____
|web| ____________ ---
|app| <-----> | | /___\
|___| | API | / \
| to | <------> / DB \
––––– | GQL | /__Mongo__\
|mob| <-----> | | | |
|ile| –––––––––––––– _VVVVVVVVV_
_|____|_
GET/posts/123
---------------------------->
Post details
<---------------------------------------------------
Ex. A post renderingGET/posts?author=3233
---------------------------->
Posts by Author -server determines
what data to is sent back
<---------------------------------------------------
It lets the client describe exactly what data it needs from the
server and the server sends it back.
Instead of requesting one at a time, I can request the post details, other
posts by that author, any post comments, all within a single GQL request.
It lets the client determine what data gets back, instead of the server determinining what data it should sent back.
Fewer HTTP requests, flexible data querying and less code to manage.
Refers about how data relates to other data.
Data to store such as a User type, Comment type, or a Post type, and needed
when we need to define/create an API.
Ex:
User type -------> id (string), name (string)
Post type -------> id (string), title (string), published (boolean)
Comment type ---->. id (string), text (string)
A User can have many posts.
A Post belongs to a User.
A Post can have many comments.
A Comment associated with a Post.
A User can have many comments.
A Comment always belong to a User.
/* Query
----- */
Querying objects, we need to specify fields we want
query {
users {
name
email
id
posts {
id
title
body
published
}
}
}
/*
Data
-----
*/
{
"data": {
"users": [
{
"name": "Andrew",
"email": "andrew@example.com",
"id": "64566edb-06c0-4f3d-8f71-997d86d77342",
"posts": [
{
"id": "995186c3-40d4-428d-835e-0b4ea53a97f7",
"title": "GraphQL 101",
"body": "This is how to use GraphQL...",
"published": true
},
{
"id": "1d982e9d-78f9-4518-89ee-efb107f1c55e",
"title": "GraphQL 201",
"body": "This is an advanced GraphQL post...",
"published": false
}
]
},
]
}
}