首页 > 解决方案 > 自定义指令的非原始类型属性

问题描述

我有一个关于 graphql 模式定义的问题。

可以将非原始类型定义为指令的属性吗?如果是,那么在字段上使用指令时的语法是什么?

例如,有一个 Url 类型定义如下:

type Url {
   address: String!
   desription: String
}

和一个指令

@custom_directive { 
    url: Url!
} on FIELD_DEFINITION

然后如何在字段上使用该指令?

type AnotherType {
    field: SomeOtherType @custom_directive(url: ???)
}

谢谢

标签: graphqlgraphql-java

解决方案


是的。您可以将非标量类型定义为指令中的属性,但它应该是Input类型:

input UrlInput {
   address: String!
   desription: String
}

而且您在directive声明时也会错过保留字。它应该是:

directive @custom_directive (url:UrlInput!) on FIELD_DEFINITION

在字段上对其进行注释:

type AnotherType {
    field: SomeOtherType @custom_directive (url : {address: "foo" description: "bar"})
}

给定 a GraphQLSchema,您可以通过以下方式访问在给定字段上注释的指令值:

    Map<String, Object> value  = (Map<String, Object>) graphQLSchema
       .getObjectType("AnotherType")
       .getFieldDefinition("field")
       .getDirective("custom_directive")
       .getArgument("url").getValue();

    value.get("address") //foo 
    value.get("description") //bar

您还可以实现 aSchemaDirectiveWiring并覆盖它onField(),在构建期间将调用此指令标记的字段GraphQLSchemaGraphQLFieldDefinition在此方法中,您可以根据该指令中配置的值更改此字段。(例如修改其数据获取器等)

SchemaDirectiveWiring在构建时由以下内容注册RuntimeWiring

RuntimeWiring.newRuntimeWiring()
.directive("custom_directive", new MySchemaDirectiveWiring())
.build();

推荐阅读