【问题标题】:Non primitive type attribute for custom directive自定义指令的非原始类型属性
【发布时间】:2020-02-11 04:53:23
【问题描述】:

我有一个关于 graphql 架构定义的问题。

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

比如说有一个Url类型定义如下:

type Url {
   address: String!
   desription: String
}

还有一个指令

@custom_directive { 
    url: Url!
} on FIELD_DEFINITION

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

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

谢谢

【问题讨论】:

    标签: graphql graphql-java


    【解决方案1】:

    是的。您可以将非标量类型定义为指令中的属性,但它应该是 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"})
    }
    

    给定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
    

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

    SchemaDirectiveWiring 在构建RuntimeWiring 时由以下注册:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-30
      • 1970-01-01
      • 2016-04-04
      • 2020-10-27
      • 1970-01-01
      相关资源
      最近更新 更多