代码之家  ›  专栏  ›  技术社区  ›  tryingHard

graphql使用输入类型搜索数据

  •  0
  • tryingHard  · 技术社区  · 7 年前

    使用时搜索有问题 Input data 在里面 graphql :

    @RestController
    @RequestMapping("/api/dictionary/")
    @RequiredArgsConstructor(onConstructor = @__(@Autowired))
    public class DictionaryController {
        @Value("classpath:items.graphqls")
        private Resource schemaResource;
        private GraphQL graphQL;
        private final DictionaryService dictionaryService;
    
        @PostConstruct
        public void loadSchema() throws IOException {
            File schemaFile = schemaResource.getFile();
            TypeDefinitionRegistry registry = new SchemaParser().parse(schemaFile);
            RuntimeWiring wiring = buildWiring();
            GraphQLSchema schema = new SchemaGenerator().makeExecutableSchema(registry, wiring);
            graphQL = GraphQL.newGraphQL(schema).build();
        }
    
    private RuntimeWiring buildWiring() {
    
                DataFetcher<String> fetcher9 = dataFetchingEnvironment ->
                getByInput((dataFetchingEnvironment.getArgument("example")));
    
            return RuntimeWiring.newRuntimeWiring()
                    .type("Query", typeWriting ->
                       typeWriting
                        .dataFetcher("getByInput", fetcher9)
                        )
                    .build();
        }
    
    
    public String getByInput(Character character) {
        return "testCharacter";
    }
      }
    

    items.graphqls 文件内容:

    type Query {
       getByInput(example: Character): String
    }
    
    input Character {
        name: String
    }
    

    当要求这样的资源时:

    query {
        getByInput (example: {name: "aa"} )
    }
    

    字符DTO:

    @NoArgsConstructor
    @AllArgsConstructor
    @Data
    public class Character {
        protected String name;
    }
    

    我有个错误:

    "Exception while fetching data (/getByInput) : java.util.LinkedHashMap cannot be cast to pl.graphql.Character",
    

    查询应该是什么样子?

    编辑

    如果我改为:

    public String getByInput(Object character) 
    

    代码运行良好-但我想转换为工作。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Ken Chan    7 年前

    对于类型为的输入参数 input 类型, graphql-java 将其转换为 Map .

    在您的案例中,查询是 getByInput (example: {name: "aa"} ) 哪一个 example 论证是 输入 类型。所以,

    dataFetchingEnvironment.get("example");
    

    将返回具有结构的映射(key=“name”,value=“a a”)。然后尝试将映射强制转换为 Character 这肯定会给你一个错误,因为它们是完全不同的类型。

    将地图转换为 性格 , Java语言 对你这样的转变没有帮助。您必须自己实现转换代码或使用其他库,例如 Jackson , Gson , Dozer or whatever libraries you like 用于将映射转换为域对象(即字符)。