Example GraphQL Server for Complex Query
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/
Access GraphQL console http://localhost:4000
Input query:
{
users {
id
username
profile {
name
email
}
status
}
}
Click run
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] } })
_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
products(where: { price: { _between: [2000, 5000] } }, order_by: { id: desc })
users(order_by: { profile__name: desc })
products(where: { price: { _between: [2000, 5000] } }, order_by: { id: desc }, limit: 1)
users(limit: 3 )
products(limit: 2, offset: 1)
Assumption: default field name for primary key is id
, but You can change it.
users(pk: "username")
- 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
- Only support single primary key or not support composite key
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);
});