You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Netflix DGS框架中隐藏GraphQL字段?以Show类型title字段为例

在DGS框架中隐藏GraphQL字段的方法

针对你定义的Show类型,要让title字段对客户端不可见或无法获取,有以下几种实用方法:

  • 使用@DgsIgnore注解
    在字段对应的数据获取方法上添加@DgsIgnore注解,DGS框架会直接忽略该字段,客户端无法查询到它。示例代码如下:

    @DgsComponent
    public class ShowDataFetcher {
        @DgsQuery
        public Show fetchShow() {
            return new Show("Demo Title", Arrays.asList(new Actor("Tom")));
        }
    
        // 给title字段的获取方法添加@DgsIgnore,客户端无法获取该字段
        @DgsData(parentType = "Show", field = "title")
        @DgsIgnore
        public String getShowTitle(DgsDataFetchingEnvironment env) {
            Show show = env.getSource();
            return show.getTitle();
        }
    }
    
  • 直接修改GraphQL Schema
    最直接的方式是在Schema定义中移除或注释掉title字段,这样客户端的Schema定义里就不会存在该字段,自然无法发起查询。修改后的Schema:

    type Show {
      # title: String  # 注释或直接删除该字段
      actors: [Actor]
    }
    
  • 通过Schema Transform动态隐藏
    如果需要根据业务条件(比如用户权限)动态控制字段可见性,可以实现DgsSchemaTransformer接口来修改Schema,动态移除title字段:

    @Component
    public class HideTitleTransformer implements DgsSchemaTransformer {
        @Override
        public GraphQLSchema transform(GraphQLSchema schema) {
            ObjectType originalShowType = (ObjectType) schema.getType("Show");
            // 过滤掉title字段
            List<Field> filteredFields = originalShowType.getFields().stream()
                    .filter(field -> !field.getName().equals("title"))
                    .collect(Collectors.toList());
            // 构建新的Show类型
            ObjectType updatedShowType = ObjectType.newObject(originalShowType)
                    .fields(filteredFields)
                    .build();
            // 返回修改后的Schema
            return GraphQLSchema.newSchema(schema)
                    .additionalType(updatedShowType)
                    .build();
        }
    }
    

内容的提问来源于stack exchange,提问作者Bongo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 13:16:59