问题
I have problem searching with using Input data
in 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
file content:
type Query {
getByInput(example: Character): String
}
input Character {
name: String
}
When asking for resource like that:
query {
getByInput (example: {name: "aa"} )
}
Character DTO:
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Character {
protected String name;
}
I've got an error:
"Exception while fetching data (/getByInput) : java.util.LinkedHashMap cannot be cast to pl.graphql.Character",
How should the query look like?
Edit
If i change to:
public String getByInput(Object character)
The codes runs fine - but i want convert to work.
回答1:
For the input argument which the type is the input
type , graphql-java
will convert it to a Map
.
In your case the query is getByInput (example: {name: "aa"} )
which the example
argument is the input
type . So ,
dataFetchingEnvironment.get("example");
will return a Map with the structure (key="name" , value="aa") .Then you try to cast the map to Character
which definitely gives you an error since they are totally different types.
To convert a Map to a Character
, graphql-java
will not help you for such conversion. You have to implement the conversion codes by yourselves or use other libraries such as Jackson , Gson , Dozer or whatever libraries you like for converting a map to your domain object (i.e. Character).
来源:https://stackoverflow.com/questions/54257346/graphql-use-input-type-to-search-data