Đang học về GraphQL và Drupal 9 quá hay Encapsulation

5th May 2022
Table of contents

GraphQL talks to Drupal in HTTP and the outputs are more structured than ever before!

Today, great customer experiences begin with great content. Content that is made available everywhere. With Drupal 8’s API-first initiative, the content that is managed by Drupal can be readily used by other systems over HTTP. REST (Representational State Transfer) provides a design standard for APIs. However, with client applications getting more complex and challenging, developers need a more modern and effective solution.

GraphQL was born out of the demand for a more flexible and powerful client-server interaction. It is a sophisticated query language and an execution machine. In 2012 Facebook created the specification for it, which describes its capabilities and the requirements of data models for headless applications.

What is GraphQL?

GraphQL is an adaptive standard for APIs and provides a runtime to fulfill those queries. GraphQL gives a complete and reasonable details of the information in your API. It's developed with an ideology of "Ask for what you need and get exactly that". It empowers the client to fetch for the exact response they need from the API, nothing more - nothing less.

GraphQL Advantages

Few of the many advantages of using GraphQL for Drupal

Faster frontend development

Emphasize quickly on applications without waiting for new backend endpoints. Improve data fetching and code maintenance by getting the data in the shape you need.

Ask for what you need and get exactly that

It provides the exact response the client asked for. It always returns predictable result. Applications using GraphQL are also stable because the application controls the data it gets, not the server.

Use your existing data

GraphQL can be used with any existing infrastructure e.g. REST, SOAP or existing database, or anything else. It allows you to query all the data in a single request and provides you a cleaned predictable response.

Fewer bytes and roundtrips

Using GraphQL all the required data can be fetched using single query. It’s makes the application faster.

REST vs JSON:API vs GraphQL

If we compare these three according to request efficiency, JSON:API and GraphQL are excellent. Because in a single request JSON:API and GraphQl can serve all the required responses. In case of JSON:API, sometimes we have to tailor the response but when it comes to GraphQL, it only serves what we need. REST is slower as compared to these, because multiple requests are needed to serve the common needs.

In terms of operational simplicity and implementation, REST is the easiest, it has been there for quite a while now. JSON:API also works out of the box with CDN and reverse proxies. For GraphQL extra infrastructure is needed and client libraries are necessary to implement it.

It’s easier to use web cache in REST and JSON:API as compared to GraphQL. In GraphQL, there’s only one endpoint (most of the time an HTTP POST endpoint) where all the queries are sent. Since each query can be different, it is harder to use this type of caching.

The Drupal GraphQL specification supports bulk/batch operations automatically for the mutations you've already implemented, whereas the JSON:API specification does not. The ability to perform batch write operations can be important.

Installing GraphQL for Drupal 8

The Drupal GraphQL module supports all the GraphQL specifications and can be used to build and expose GraphQL schemas. The latest alpha release of the Drupal 8 module in the version 8.x-4 offers a capability for Drupal modules to extend the schema with a plugin.

Here is where you can install Drupal GraphQL module from - https://www.drupal.org/project/graphql

You can install using composer command.

composer require 'drupal/graphql:^3.0'

It will provide you two modules GraphQL Core and GraphQL. You need to enable both the modules. You can enable it using drush e.g.

drush en graphql
drush en graphql_core

Queries with Drupal GraphQL

Drupal GraphQL module provides a tool called GraphiQL. It’s a powerful tool and has an interactive UI with functionalities like auto completion. Using this tool, you can run queries and get outputs. Navigate to – “/graphql/explorer” for the interface.

You will get a UI that looks like this

GraphiQL UI
GraphiQL UI

On the left side panel of this UI you can write a query and on the right side, you will see the results as an output in JSON format. Clicking on Docs at top right corner, will get you the documentation of the available queries. Query Variable section on the bottom left panel can be used to pass query variables.

Examples

1.Querying Nodes

Drupal GraphQL - Querying Nodes
Drupal GraphQL - Querying Nodes

2. Querying Taxonomies

Drupal GraphQL - Querying Taxonomies
Drupal GraphQL - Querying Taxonomies

3. Querying Routes

Drupal GraphQL - Querying Routes
Drupal GraphQL - Querying Routes

4. Query Fragments

Drupal GraphQL - Query Fragments
Drupal GraphQL - Query Fragments

5.Filters

Drupal GraphQL - Filters
Drupal GraphQL - Filters

6. Filters with conjunction

Drupal GraphQL - Filters with Conjunction
Drupal GraphQL - Filters with Conjunction

Other available operators are:

  1. EQUAL
  2. NOT_EQUAL
  3. SMALLER_THAN
  4. SMALLER_THAN_OR_EQUAL
  5. GREATER_THAN
  6. GREATER_THAN_OR_EQUAL
  7. IN
  8. NOT_IN
  9. LIKE
  10. NOT_LIKE
  11. BETWEEN
  12. NOT_BETWEEN
  13. IS_NULL
  14. IS_NOT_NULL

Conjunctions can have two values

  1. AND
  2. OR

You can also use Groups to write more complex queries.

7.GraphQL variables

Drupal GraphQL - Variables
Drupal GraphQL - Variables

Mutations

In GraphQL, a mutation is the terminology used whenever you want to add, modify, or delete data stored on the server. In this case, Drupal. Unfortunately, the module does not include a way to perform common mutations out of the box due to some technical requirements of GraphQL.
Example code for creating, deleting, updating, and file uploads, can be found here: https://github.com/drupal-graphql/graphql-examples

Example mutation:

Drupal GraphQL - Mutation example
Drupal GraphQL - Mutation example

Drupal GraphQL with Twig

Using Drupal GraphQL with Twig can significantly improve the performance of your website. Here’s how – When you inject data into the Twig template, you can fetch all the required data using a single API call. Moreover, because the client controls the data they get and not the server, it makes the process even faster.

To use Drupal GraphQL with Twig we need the GraphQL Twig module. To download and enable it, use the following commands:

composer require 'drupal/graphql_twig:^1.0'
drush en graphql_twig

And then you can use GraphQL query in your website e.g.

{#graphql
query {
  admin:userById(id: "1") {
    uid
    name
  }
  user:currentUserContext {
    uid
  }
}
#}

You will get the response data in the GraphQL variable.


Add new comment

This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.

Image CAPTCHA
Enter the characters shown in the image.
Câu nói tâm đắc: “Điều tuyệt với nhất trong cuộc sống là làm được những việc mà người khác tin là không thể!”

Related Articles

There’s no denying that GraphQL is the latest addition for API development. For front end frameworks many GraphQL clients are available and Apollo

However, there is one case that the Graphql module does not cover: building a Graphql schema for data that is not represented as a Drupal entity.

Over the past decade, REST has become the standard (yet a fuzzy one) for designing web APIs

The same route handler function is called in REST whereas in GraphQL query can be called to form nested response with multiple resources.

This session will introduce GraphQL queries and demonstrate the advantages of changing the Drupal push model to a pull model by letting the template define its data requirements