构建自定义指令
创建您自己的模式指令,为 GraphQL 字段添加自定义逻辑、验证或转换。
构建自定义指令 是 CoddyKit 上的免费 GraphQL APIs with Spring Boot 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 GraphQL APIs with Spring Boot 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 GraphQL APIs with Spring Boot 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
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 | FIELDUnderstanding 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_DEFINITIONWiring 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
@logexample.
Custom directives are powerful for adding reusable, cross-cutting concerns to your API.
常见问题解答
「构建自定义指令」课时是免费的吗?
是的 — 「构建自定义指令」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 GraphQL APIs with Spring Boot 课程的其余内容,请升级到 CoddyKit PRO。 GraphQL APIs with Spring Boot 课程共包含 4 节课。
「构建自定义指令」这节课中我会学到什么?
创建您自己的模式指令,为 GraphQL 字段添加自定义逻辑、验证或转换。 你通过在浏览器中直接运行的动手代码来练习 GraphQL APIs with Spring Boot,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 GraphQL APIs with Spring Boot 需要有经验吗?
无需任何先前经验。CoddyKit 上的 GraphQL APIs with Spring Boot 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「构建自定义指令」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 GraphQL APIs with Spring Boot 课中编写并运行代码吗?
能。每节 GraphQL APIs with Spring Boot 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。