Using GraphQL instead of REST

REST services are standard and easy to use, but may imply some overhead, mostly when you don't need just a single entity, but also some related ones; for example, how would you get a country and all of its regions? With our current design, you'd have to do separate calls and join the results by yourself, or otherwise extend your routes yourself. For example, you would do this for /regions/uy?include=cities so that the server would add—to each region in UY—an array with its cities. While this solution may be apt for a small example like the one we're using, for bigger, more complex databases, with tables related among themselves in many ways, it could easily get out of hand.

There is, however, another option. GraphQL is a data query language that was developed by Facebook, and it lets you define, at the client, the structure of the data you require; the server will do whatever is needed to produce exactly that. GraphQL lets you get many related resources with a single request by following references to build a complex structure, and sending it along with the minimum delay. You also get tools to help you define your data schema and perform online queries. 

Let's look at a very short example, taken from the documentation of GraphQL's own site, at http://graphql.org/learn/queries/. Given a database of Star Wars movies, you could write the following query that wants to get the hero from a couple of movies, and for each one, the name, the list of movies they appear in, and all of their friends' names:

{
leftComparison: hero(episode: EMPIRE) {
...comparisonFields
}
rightComparison: hero(episode: JEDI) {
...comparisonFields
}
}

fragment comparisonFields on Character {
name
appearsIn
friends {
name
}
}

The result of this query is as follows. Note how the object structure follows your specification in the query, and that repeated fields, or foreign key access, were all solved by the GraphQL server, and in a single request:

{
data: {
leftComparison: {
name: "Luke Skywalker",
appearsIn: ["NEWHOPE", "EMPIRE", "JEDI"],
friends: [
{
name: "Han Solo"
},
{
name: "Leia Organa"
},
{
name: "C-3PO"
},
{
name: "R2-D2"
}
]
},
rightComparison: {
name: "R2-D2",
appearsIn: ["NEWHOPE", "EMPIRE", "JEDI"],
friends: [
{
name: "Luke Skywalker"
},
{
name: "Han Solo"
},
{
name: "Leia Organa"
}
]
}
}
}

While totally outside the scope of this chapter (we wanted a RESTful server, after all), GraphQL is a very valid alternative for applications that need to work with complex, linked structures, which would require too much processing and communication time otherwise.

To learn more about GraphQL, check out the official site at https://graphql.org/
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.123.120