GraphQL com GoLang
GraphQLSP 01
Schema First vs Code First
Schema First
- Design the schema first (duuuh)
- A tool reads the schema and generates the code
- Types are already defined in code level (no interface{} types)
- Needs a configuration file to determine how to generate code
- Library / Tool: https://github.com/99designs/gqlgen
Code First
- Define the models in code level
- Types can only be inferred by runtime (lots of interface{} type)
- Schema is generated at runtime
- Needs some workarrounds for cyclic reference
- Library / Tool: https://github.com/graphql-go/graphql
Schema First
GraphQL Model
Generated GoLang Model
*developer calls gqlgen*
Code First
Declared GraphQL Model
Declared Golang Model
Code First Design
Pokemon GraphQL
Based on Javascript
Pokemon Gopher
- Has a cyclic reference (pokemons have evolutions)
- Search Pokemon by Name or ID
- List all first N Pokemon
- We have to deal with interface{} types
Pokemon Gopher
Go Models
Pokemon Gopher
GraphQL Models
Pokemon Gopher
GraphQL Models
Pokemon Gopher
Cyclic Reference Issue
Pokemon model has evolutions which ...
are Pokemons as well!
In Javascript, that would work fine due Lazy References.
But GoLang does not have lazy references
Pokemon Gopher
Cyclic Reference Issue
The golang init function is a built-in that runs before any code
Pokemon Gopher
Deep into Resolver
Pokemon Gopher
Deep into Resolver
Pokemon Gopher
Deep into Resolver
- Casting p.Source to models.Pokemon so we can access its fields
- Result in variable d and a boolean ok if the cast was successfull
- If the casting wasn't ok, the received model is wrong
- Return an error saying the model wasn't the one we expected
If everything is alright we can fetch the evolutions from the database
Pokemon Gopher
Queries
Pokemon Gopher
Queries
Pokemon Gopher
Queries
Pokemon Gopher
Schema
Pokemon Gopher
Program
Running
Questions?
- Twitter @lucasteske
- Telegram @lucasteske
- Github racerxdl
- Telegram @lucasteske
- Github racerxdl
Source Code: https://github.com/racerxdl/pokemon-gopher
Thanks for Watching!