graphql-server-complex-query-example
Example GraphQL Server for Complex Query
Installation
Run on terminal
git clone https://github.com/hscstudio/graphql-server-complex-query-example.git
cd grapql-server-complex-query-example
npm install
npm run dev
You will see below on terminal
> nodemon index.js
[nodemon] 2.0.7
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node index.js`
🚀 Server ready at http://localhost:4000/
Usage
Access GraphQL console http://localhost:4000
Input query:
{
users {
id
username
profile {
name
email
}
status
}
}
Click run
Example Complex Query
Where
Find users where username equal def
{
users(where: { username: { _eq: "def" } }) {
id
username
profile {
name
email
}
status
}
}
Result:
{
"data": {
"users": [
{
"id": 2,
"username": "def",
"profile": {
"name": "Def",
"email": "def@yahoo.com"
},
"status": true
}
]
}
}
Other query:
users(where: { profile__email: { _eq: "ghi@gmail.com" } })
users(where: { profile__email: { _like: "gmail" } })
products(where: { price: { _lte: 2000 } })
products(where: { _and: [{ price: { _lt: 5000 }}, { stock: { _gte: 10 }}] })
products(where: { _or: [{ price: { _lt: 5000 }}, { stock: { _gte: 10 }}] })
products(where: { price: { _between: [2000, 5000] } })
Available Operator
_eq
: equal_in
: in_array_like
: like_lt
: lower than_lte
: lower than equal_gt
: greather than_gte
: greather than equal_and
: and_or
: or_between
: between
OrderBy
products(where: { price: { _between: [2000, 5000] } }, order_by: { id: desc })
users(order_by: { profile__name: desc })
Limit
products(where: { price: { _between: [2000, 5000] } }, order_by: { id: desc }, limit: 1)
users(limit: 3 )
Offset
products(limit: 2, offset: 1)
Customize Primary Key
Assumption: default field name for primary key is id
, but You can change it.
users(pk: "username")
To Do
- Mutation
- Update
- Create
- Delete
- Generator
- Authentication
https://blog.logrocket.com/crud-with-node-graphql-react/ https://developer.okta.com/blog/2019/05/29/build-crud-nodejs-graphql
Limitation
- Only support single primary key or not support composite key
Request Using Other Tools
Postman
Javascript Axios
var axios = require('axios');
var data = JSON.stringify({
query: `{
products(where: { price: { _lte: 2000 } }) {
id
title
price
status
}
}`,
variables: {}
});
var config = {
method: 'post',
url: 'http://localhost:4000',
headers: {
'Content-Type': 'application/json'
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});