From d1018df96051e90f4b276e62764c0198f043d33b Mon Sep 17 00:00:00 2001 From: kuanghc1 Date: Sat, 18 Jun 2022 23:50:43 +0800 Subject: [PATCH] Add part of custom directives --- .../demo/directives/UppercaseDirective.java | 33 +++++++++++++++++++ src/main/resources/schema/schema.graphqls | 3 +- 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/example/demo/directives/UppercaseDirective.java diff --git a/src/main/java/com/example/demo/directives/UppercaseDirective.java b/src/main/java/com/example/demo/directives/UppercaseDirective.java new file mode 100644 index 0000000..edec196 --- /dev/null +++ b/src/main/java/com/example/demo/directives/UppercaseDirective.java @@ -0,0 +1,33 @@ +package com.example.demo.directives; + +import com.netflix.graphql.dgs.DgsDirective; +import graphql.schema.DataFetcher; +import graphql.schema.DataFetcherFactories; +import graphql.schema.GraphQLFieldDefinition; +import graphql.schema.GraphQLFieldsContainer; +import graphql.schema.idl.SchemaDirectiveWiring; +import graphql.schema.idl.SchemaDirectiveWiringEnvironment; + +@DgsDirective(name = "uppercase") +public class UppercaseDirective implements SchemaDirectiveWiring { + + @Override + public GraphQLFieldDefinition onField(SchemaDirectiveWiringEnvironment env) { + GraphQLFieldsContainer fieldsContainer = env.getFieldsContainer(); + GraphQLFieldDefinition fieldDefinition = env.getFieldDefinition(); + + DataFetcher originalDataFetcher = env.getCodeRegistry().getDataFetcher(fieldsContainer, fieldDefinition); + DataFetcher dataFetcher = DataFetcherFactories.wrapDataFetcher( + originalDataFetcher, + (dataFetchingEnvironment, value) -> { + if (value instanceof String) { + return ((String) value).toUpperCase(); + } + return value; + } + ); + + env.getCodeRegistry().dataFetcher(fieldsContainer, fieldDefinition, dataFetcher); + return fieldDefinition; + } +} diff --git a/src/main/resources/schema/schema.graphqls b/src/main/resources/schema/schema.graphqls index acf3f79..ef94535 100644 --- a/src/main/resources/schema/schema.graphqls +++ b/src/main/resources/schema/schema.graphqls @@ -14,7 +14,7 @@ type Subscription { type Show { id: Int - title: String + title: String @uppercase releaseYear: Int reviews(minScore:Int): [Review] artwork: [Image] @@ -39,3 +39,4 @@ type Image { scalar DateTime scalar Upload directive @skipcodegen on FIELD_DEFINITION +directive @uppercase on FIELD_DEFINITION