GraphQL
What is GraphQL ?
- query language
- usually we have one single endpoint (typically /graphql)
- uses POST because request body defines Data Structure of retrieved Data, so we are using POST for getting data
- server-side resolver analyses Request body, Fetches and Prepares and Returns Data
Why is it better than REST Api for some scenarios ?
- lets presume you have data of posts, which have
id
,title
andcontent
- imagine situation where you want to retrieve
id
andtitle
in one page andcontent
on another page - you can do two different endpoints or one endpoint loaded with query url
- both solutions arent very good or effective
- in GraphQL you can define on frontend, which data you want to retrieve from backend
We will create new folder graphql
under our project and under that two files schema.js
, resolvers.js
.
schema.js - here we define queries, mutations and types with which we will work in our GraphQL service
resolvers.js - here we logic which will be executed for queries
graphql/schema.js
graphql/resolvers.js
app.js
Now make POST
request from your favourite client, for example Insomnia
.
POST http://localhost:3000/graphql
You should get following output:
Also if you are using graphiql: true
, you can go to http://localhost:3000/graphql
in your browser where you will have graphql playground console.