GraphQL advanced concepts 💥💥

(Feb Blog)

Introduction 🙋

Hi, this is my second blog about GraphQL (2020 Blogging challenge )

In this article, I’m going to share with you some advanced concepts that I’ve learned about GraphQL.

First ! Graphql subscriptions 💥💥:

While discovering GraphQL’s core concepts, I found out that if the client wants to fetch or send data to the server, there are queries and mutations that should be used, as for real-time messages and interactions there is “GraphQL subscriptions”.

“GraphQL subscriptions are a way to push data from the server to the clients that choose to listen to real-time messages from the server”

Example Graphql subscriptions App design

Validations in GraphQL🚩:

While adding or modifying data, it is important to validate user input.

@Non-null Validation :

The fields whose types have an exclamation mark ! are the non-null fields

@Custom Validation :

For Custom Validation like mail-validation, checking string’s length, checking if a number is within a given range we can implement custom validators.

The custom validation logic will be a part of the resolver function.

  • Solution 1 with Resolvers :
  1. Define our schema.graphql

2. Create the Resolver :

3. Run the Application:

query variable

The errors array contains the details of validation errors:

Solution 2 with schema directives:

We can use graphql-constraint-directive which allows using @constraint as a directive to validate input data.

Example of how to use it :

Authentication with GraphQL 🔓 🔏:

Like REST API, we should always care about who will interact with our GraphQL server, who is authorized to send queries and run mutations or subscriptions!

It’s not so different from the other approaches!

Example 1: Authentication with GraphQL using

Example 2: Authentication with GraphQL using

Paginating and sorting with GraphQL 📃 📑:

Pagination :

Pagination is a tricky topic in API design. On a high-level, there are two major approaches regarding how it can be tackled

Limit-Offset: Request a specific chunk of the list by providing the indices of the items to be retrieved (in fact, you’re mostly providing the start index (offset) as well as a count of items to be retrieved (limit)).

Cursor-based: This pagination model is a bit more advanced. Every element in the list is associated with a unique ID (the cursor). Clients paginating through the list then provide the cursor of the starting element as well as a count of items to be retrieved.

Implement Pagination with Prisma :

  1. Define in our schema.graphql (add params `skip start index ` and `first the first x elements after a provided start index` to our query feed )

2. adjust the implementation of the resolver:

3. Test the pagination API :


With Graphql API Design, it is possible to return lists of elements that are sorted (ordered) according to specific criteria

  1. Add the following enum definition to :

2. adjust the query again to include the argument:

3. adjust the implementation of the resolver:

4. Test your query :

Fragments, Interfaces, and Unions in GraphQL 📀 📼:

“Reducing the schema complexity”

What are Fragments?

A fragment is basically a reusable piece of the query.

Fragments are a handy feature to help to improve the structure and reusability of your GraphQL code. A fragment is a collection of fields on a specific type.

Simple GraphQL Query without fragment :

Define Fragment:

Adding Fragment to Query code :

Interfaces in GraphQL?

Interface in programming: The interface is a structure that enforces certain properties on the object or class that implements the corresponding interface

Unions in GraphQL?

The Union type indicates that a field can return more than one object type

Error handling with GraphQL 🚫 ❌ :

Before we talk about how to handle errors in GraphQL, let’s identify what types of errors that we can get :

  1. Server problems (5xx HTTP codes, 1xxx WebSocket codes)
  2. Client problems e.g. rate-limited, unauthorized, etc. (4xx HTTP codes)
  3. The is missing/malformed
  4. The fails GraphQL internal validation (syntax, schema logic, etc.)
  5. The user-supplied or is bad and the / function intentionally throws an error (e.g. not allowed to view requested user)
  6. An uncaught developer error occurred inside the / function (e.g. poorly written database query)

And the problem with Graphql gives you a result with , even if that result contains , it is not an error! that’ why we should handle it

Example 1 of Implementation with Apollo-server :

Apollo Server provides a collection of predefined errors, including , , , and a generic

the response :

UserInputError Example :

and you will get a response like this :

Batching in GraphQL 📟:

“Batching is the process of taking a group of requests, combining them into one, and making a single request with the same data that all of the other queries would have made”

Caching in GraphQL 💲:

Caching is the process of storing data in a temporary storage area called cache.

In an endpoint-based API, clients can use HTTP caching to easily avoid refetching resources, and for identifying when two resources are the same.

There are three types of caching that can be involved in an endpoint-based API :

  • Client Caching: is the process of caching data in the client-side browser that helps to limit the data cost incurred by the user by keeping commonly referenced data locally. The client often requests data that may not be large but is indeed continuously needed
  • Network Caching: they intercept requests that look the same (based on various configurable criteria), returning a response early straight out of memory, instead of hitting the application serve
  • Application Caching: It can be implemented in the application with tools like Memcache, Redis, etc… one of the advantages for example if the remote server is not available due to a crash or network partitioning, the client can obtain a cached copy at the proxy. Hence, the robustness of the Web service is enhanced.

For the case of Graphql, there is no Network caching because all our interactions (queries or mutations ) with GraphQL API it will be with a single endpoint 🔧 🔨

So the caching needs to be done in the application and it’s recommended for the graphql website to be done into the client-side

Technical solution: “DataLoader” 📘 📙

a generic utility to be used as part of your application’s data fetching layer to provide a consistent API over various backends and reduce requests to those backends via batching and caching.

— — →What I have got from learning developers feedback it that “GraphQL definitely needs a better caching system to win the GraphQL vs REST war.”⚡️⚡️⚡️

GraphQL tools :

And before ending this Blog, This a lits of useful tools that can help you as a GraphQl developer to speed up your work or to tets it perfectly

  1. GraphiQL — making GraphQL easier
  2. GraphQL Voyager : visualize your GraphQL
  3. GraphQL Docs : — auto-create your docs
  4. GraphQL IDE — the GraphQL playground
  5. Graphql-network: Chrome Devtool that provides a “network”-style tab for GraphQL requests to allow developers to debug more easily.
  6. Graphql-code-generator: GraphQL code generator with flexible support for custom plugins and templates
  7. swagger-to-graphql Swagger to GraphQL API adapter
  8. Prisma Modern DB toolkit to query, migrate and model your database

Conclusion :

For conclusion, GraphQL was one of the priority skills and technologies that I fixed to learn in 2020, I just started with core concepts, and discover the all whole ecosystem, in parallel, I’m trying to practice and implement some “POCS” by creating this repo:

Happy Learning :)