This is a GraphQL example for the GraphQL meetup in Rome.
We are going to use the reference implementation of GraphQL for JavaScript.
To start the tutorial:
- clone this repository
git checkout 1.0.1
This is the data model we would like to define:
+----------------------------------+ +----------------------------+ +---------------------+
| QueryType | | ReservationType | | HotelType |
+----------------------------------+ +----------------------------+ +---------------------+
| | | | | |
| reservations: [ReservationType]! +-------> | reservationNumber: ID! | | hotelName: String! |
| | | checkIn: String! | | fullAddress: String |
+----------------------------------+ | checkOut: String! | | starRating: Int! |
| hotel: HotelType! +-------> | |
| status: ReservationStatus! | +---------------------+
| |
+----------------------------+
Using the GraphQL SDL (i.e. schema definition language), the data model can be described in this way:
Resolvers definition:
Loading the executable schema:
This is the recipe:
...and then start the server with the command: node ./src/index.js
First query:
{
reservations(userId: 4115) {
reservationNumber,
checkIn,
checkOut
}
}
Try the first query in the browser.
The GraphQL introspection feature is the ability of exposing information about what queries are supported. Example introspection query:
{
__schema {
types {
name,
description
}
}
}
Try the GraphQL the introspection query.
This feature leads to really nice features like:
- Auto documentation: the client knows the exact GraphQL schema.
- Code generation: the client can use a client generated from the schema.
- Static validation: the GraphQL client can validate the query before sending it to the server
GraphiQL is a Schema Explorer that use the GraphQL introspection feature.
git checkout 1.0.2
- restart the server and access to GraphiQL
Introduce an additional resolver in order to gather hotel data from the HotelService
:
git checkout 1.0.3