Professional Documents
Culture Documents
graphQL Essencial
graphQL Essencial
• Conclusion
STEPHEN BARLOW
DOCUMENTATION LEAD, APOLLO GRAPHQL
BENEFITS OF GRAPHQL
Table 1
BENEFIT DESCRIPTION
year Mutation:
}
} mutation {
} createReview(userId: "20", movieId: "16", rating:
5) {
movie {
And here’s a variables object that’s provided alongside that query:
title
{ similar(limit: 2) {
"similarLimit": 1 }
}
}
user {
name
Result: }
rating
{
}
"data": {
}
"moviesByTitle": [
{
"title": "Matrix Reloaded, The", Result:
"similar": [
{ {
} "movie": {
] "title": "Casino",
} "similar": [
] {
type Mutation {
Input type:
createReview(userId: ID!, movieId: ID!, rating:
Int): UserReview input ReviewInput {
} rating: Int!
movieId: ID!
userId: ID!
Note that the mutation returns a UserReview object. This means that
}
you can access any of the fields available on Movie and User (in a
nested fashion).
type Query {
{
personByName(name: String!): [PersonResult]
"data": {
}
"createReview": {
"movie": { union PersonResult = User | Actor
"title": "Casino"
}, PersonResult can be either a User or Actor. In this case, an inline
"user": { fragment can be used to fetch the appropriate fields for each type in
"name": "Nicole Ramsey" the union:
},
"rating": 5 {
Result: DIRECTIVES
GraphQL directives enable static and dynamic schema modification.
{
Here are two built-in directive examples:
"data": {
"personByName": [
@skip @include
{
"name": "Tom Cruise", query query
myMovieQuery($testValue: myMovieQuery($testValue:
"movies": [
Boolean!) { Boolean!) {
{
experimentalField @ experimentalField @
"title": "Risky Business" skip(if: $testValue) include(if: $testValue)
}, } }
{
In this example, In this example,
"title": "Cocktail" experimentalField is queried experimentalField is queried
}, only if the variable $testValue if the variable $testValue has
{ has the value false. the value true.
"title": "Top Gun"
} Learn more about directives here.
]
} SECURING YOUR GRAPHQL APIS
] Failing to secure APIs properly can have serious consequences,
} especially with GraphQL. Because clients can craft complex queries,
} servers must be ready to handle such queries. Certain queries might
be abusive or malicious, or they might simply be very large. In all of
SUBSCRIPTIONS these cases, the query can potentially bring down your GraphQL server.
Often, clients want to receive updates from the server when certain GraphQL recommends a few guidelines and strategies.
data changes. In addition to queries and mutations, GraphQL supports
TIMEOUT
a third operation type, subscription, which allows a client to subscribe
Setting a timeout informs a server and any intermediaries of the
to receive event updates. Subscriptions are real-time streaming chunks
maximum amount of time they can spend to execute any query. If a
of data that allow bi-directional interaction over a single persistent
query exceeds this maximum, the server ceases execution.
connection (often WebSocket).
Let's say a client wants to receive updates when a user submits a movie LIMITING MA XIMUM QUERY DEPTH
rating for a particular movie. If the user is viewing a movie page, the UI GraphQL schemas are often cyclic graphs, meaning a malicious GraphQL
would update when a new rating is received. query can exploit nested relationships. For example, let’s say there’s an
Entertainment API that exposes an Actor type. Each Actor can belong
Every time the underlying MovieReviewSubscription is changed, the to a Movie, and each Movie can have an Actor in the form of an Artist.
new value for rating will be pushed over WebSocket (or some other Considering this, a deeply nested query such as the following is valid:
type of persistent connection). The nature of operations performed by
subscription is slightly different than that of query — the former has Figure 1
Subscription operation:
A circular reference like this can lead to significant load on API servers. Assuming that the client making the query above isn’t authenticated,
they can access all of the user’s data, which breaches user privacy. The
GraphQL servers can enforce depth-limiting caps to control the amount
problem above is solved by adding a permission on the query, object,
of nesting that can be present in any given query. Before the query is
and field level.
processed, its depth is calculated (the above query has six nesting
levels). If the nesting depth exceeds the given limit, it is rejected Permission on field level allows you to add a check over the field. Let’s
outright. say for the object User, some fields can be viewed by anyone like name,
but we don’t want to show the field Booking, as this data is considered
QUERY COMPLEXITY LIMITS private and only accessible by the User or Admin.
Another troublesome query relates to complexity — for example, a
client can simply request many fields on the root query object. Figure 4
Figure 2
To deal with this kind of query, GraphQL has built-in support for
complexity analysis. An arbitrary number can be assigned as points to
Logic inside resolver:
any field. When an incoming query is received, these arbitrary numbers
are summed. If the total exceeds the threshold, an appropriate error Figure 5
message is returned.
FIELD-BASED PERMISSIONS
Given a schema with the objects Users, Bookings, and Movies, the
Bookings and Users objects are private, so authentication is needed to
access them. Authentication is handled by resolvers. The Movies object
is public and can be accessed without being authenticated. Now, what
should happen with the query below if the client is not authenticated?
When a field is restricted and used in a GraphQL operation, the
Figure 3 consumer receives an error response (e.g., 400 Bad Request).
CONCLUSION
While this Refcard covered the primary benefits of GraphQL and
introduced some essential GraphQL concepts, as well as more
advanced fundamentals, there are still many topics left to explore.
Below is an overview of additional resources available to learn more
about GraphQL and tools to simplify the process of building GraphQL
applications:
Copyright © 2022 DZone, Inc. All rights reserved. No part of this publication
may be reproduced, stored in a retrieval system, or transmitted, in any form or
by means of electronic, mechanical, photocopying, or otherwise, without prior
written permission of the publisher.