GraphQL APIs with Spring Boot · Leçon

Créer des directives personnalisées

Créez vos propres directives de schéma pour ajouter une logique personnalisée, une validation ou une transformation à vos champs GraphQL.

Leçon 1 sur 411 étapes

Créer des directives personnalisées est une leçon GraphQL APIs with Spring Boot gratuite sur CoddyKit. Ceci est la leçon 1 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage GraphQL APIs with Spring Boot, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours GraphQL APIs with Spring Boot comprend 4 leçons au total.

Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.

Directives: Extending GraphQL

GraphQL directives are powerful tools that allow you to add custom behavior or metadata to your schema. You might already know built-in directives like @deprecated or @skip.

Custom directives let you define your own, extending GraphQL's capabilities to fit your unique application needs.

Power of Custom Directives

Custom directives offer several benefits:

  • Reusability: Apply the same logic across multiple fields or types without repeating code.
  • Separation of Concerns: Keep business logic separate from schema definitions.
  • Cross-Cutting Concerns: Easily add features like logging, authorization, or validation to many parts of your API.

Declaring Your Directive

You define a custom directive using the directive keyword in your Schema Definition Language (SDL).

It specifies the directive's name, arguments (optional), and the locations where it can be applied.

directive @log(message: String = "Access") on FIELD_DEFINITION | FIELD

Understanding Directive Locations

The on keyword specifies where your directive can be used. Common locations include:

  • FIELD_DEFINITION: On a field within a type (e.g., User.name).
  • FIELD: On a field in a query document (client-side).
  • ARGUMENT_DEFINITION: On an argument of a field or input field.
  • OBJECT: On an object type.

Implementing Directive Logic

To make your custom directive do something, you need to "wire" it to your Spring Boot application. This involves telling graphql-java how to handle the directive when it encounters it in the schema.

We'll use SchemaDirectiveWiring to intercept and modify field resolution.

Example: The @log Directive

Let's create a @log directive that prints a message whenever a field it's applied to is resolved. This is a great way to see directives in action.

First, our schema definition:

type Query {
  hello: String @log(message: "Hello field accessed")
  goodbye: String
}

directive @log(message: String = "Default Log") on FIELD_DEFINITION

Wiring the @log Directive (Part 1)

In Spring Boot, you implement SchemaDirectiveWiring and register it. This class will contain the logic to execute when the directive is found.

We'll focus on onField to intercept field resolution.

package com.coddykit.directives;

import graphql.schema.DataFetcher;
import graphql.schema.DataFetcherFactories;
import graphql.schema.GraphQLFieldDefinition;
import graphql.schema.idl.SchemaDirectiveWiring;
import graphql.schema.idl.SchemaDirectiveWiringEnvironment;
import org.springframework.stereotype.Component;

@Component
public class LogDirective implements SchemaDirectiveWiring {

    @Override
    public GraphQLFieldDefinition onField(
            SchemaDirectiveWiringEnvironment<GraphQLFieldDefinition> environment) {

        GraphQLFieldDefinition field = environment.getElement();
        String message = (String) environment.getDirective()
                                             .getArgument("message")
                                             .getValue();

        DataFetcher originalDataFetcher = environment.getFieldDataFetcher();
        DataFetcher newDataFetcher = DataFetcherFactories
            .wrapDataFetcher(originalDataFetcher, (dataFetchingEnvironment, value) -> {
                System.out.println("LOG: " + message + " for field '" + field.getName() + "'");
                return value;
            });

        environment.getFieldAndContainer().setDataFetcher(newDataFetcher);
        return field;
    }
}

Wiring the @log Directive (Part 2)

To ensure our LogDirective is picked up, we need a main application and a resolver. Here's how it all fits together, including a simple data fetcher for our hello field.

Notice how RuntimeWiringConfigurer is used to register directive wirings.

package com.coddykit;

import com.coddykit.directives.LogDirective;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.graphql.execution.RuntimeWiringConfigurer;
import org.springframework.stereotype.Controller;
import org.springframework.graphql.data.method.annotation.QueryMapping;

@SpringBootApplication
@Controller
public class Main {

    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }

    @QueryMapping
    public String hello() {
        return "Hello from CoddyKit!";
    }

    // This bean registers our custom directive wiring
    @Bean
    public RuntimeWiringConfigurer runtimeWiringConfigurer(LogDirective logDirective) {
        return builder -> builder.directive("log", logDirective);
    }
}
// For this application to run, the LogDirective class (from Scene 7)
// must be present in 'com.coddykit.directives' package.

Testing the Directive

With the application running, send a GraphQL query like this:

When you query the hello field, you'll see "LOG: Hello field accessed for field 'hello'" printed in your server console, demonstrating our custom directive in action!

query {
  hello
}

Quick Check: Directive Power

You've seen how custom directives add logic to your GraphQL schema. Which of the following best describes a primary benefit of using custom directives?

Recap: Building Directives

In this lesson, you learned to define and implement custom GraphQL directives in a Spring Boot application. We covered:

  • Declaring directives in SDL with on LOCATION.
  • Implementing directive logic using SchemaDirectiveWiring.
  • Applying a directive to modify field behavior, like our @log example.

Custom directives are powerful for adding reusable, cross-cutting concerns to your API.

Gratuit pour commencer

Apprends GraphQL APIs with Spring Boot avec un tuteur IA — gratuit

Écris et exécute du vrai code dans ton navigateur, obtiens de l'aide instantanée d'un tuteur IA disponible 24h/24, et reprends là où tu t'es arrêté sur le web ou dans l'app.

Cours
12
Leçons
48

Questions Fréquemment Posées

La leçon « Créer des directives personnalisées » est-elle gratuite ?

Oui — le texte complet de « Créer des directives personnalisées » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours GraphQL APIs with Spring Boot, passe à CoddyKit PRO. Le cours GraphQL APIs with Spring Boot comprend 4 leçons au total.

Qu'est-ce que j'apprendrai dans « Créer des directives personnalisées » ?

Créez vos propres directives de schéma pour ajouter une logique personnalisée, une validation ou une transformation à vos champs GraphQL. Tu pratiques GraphQL APIs with Spring Boot avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.

Dois-je avoir de l'expérience pour commencer GraphQL APIs with Spring Boot ?

Aucune expérience préalable n'est requise. GraphQL APIs with Spring Boot sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 1 sur 4.

Combien de temps prend la leçon « Créer des directives personnalisées » ?

La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.

Peux-tu écrire et exécuter du code dans cette leçon GraphQL APIs with Spring Boot ?

Oui. Chaque leçon GraphQL APIs with Spring Boot inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.

Toutes les leçons de ce cours

  1. Créer des directives personnalisées
  2. Principes fondamentaux de la composition de schémas
  3. Fusionner plusieurs schémas GraphQL
  4. Modulariser un schéma avec des extensions de types
← Retour à GraphQL APIs with Spring Boot