Graphql使用输入类型来搜索数据

时间:2019-01-18 15:52:47

标签: java graphql graphql-java

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 个答案:

答案 0 :(得分:1)

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

在您的情况下,查询为getByInput (example: {name: "aa"} ),其中example参数为input类型。所以,

dataFetchingEnvironment.get("example");

将返回一个结构为(key =“ name”,value =“ aa”)的Map。然后,您尝试将地图强制转换为Character,因为它们是完全不同的类型,因此肯定会给您带来错误。

要将地图转换为Charactergraphql-java将无济于事。您必须自己实现转换代码,或使用其他库(例如Jackson , Gson , Dozer or whatever libraries you like )将地图转换为域对象(即字符)。