【问题标题】:Graphql use Input type to search dataGraphql 使用 Input 类型搜索数据
【发布时间】:2019-06-12 22:01:12
【问题描述】:

graphql 中使用Input data 搜索时遇到问题:

@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) 

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

【问题讨论】:

    标签: java graphql graphql-java


    【解决方案1】:

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

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

    dataFetchingEnvironment.get("example");
    

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

    要将 Map 转换为 Charactergraphql-java 不会帮助您进行此类转换。您必须自己实现转换代码或使用其他库(例如Jackson , Gson , Dozer or whatever libraries you like )将地图转换为您的域对象(即字符)。

    【讨论】:

    • 那么input 类型在grapql 中有什么用处?也许我没有正确理解它。但在我看来,处理来自object / map 的自定义转换需要做很多工作。通常你会以其他方式使用它吗?我真的无法理解 - 为什么我要输入 Charactergrapql 不会在我的代码中搜索这个 class 以使其匹配和投射等。现在有点傻。
    • 这就是为什么输入类型适合:stackoverflow.com/questions/41743253/…。如果您认为将地图转换为您的领域对象需要做太多工作,这就是您需要一个库来帮助您的原因。我个人使用杰克逊进行这种转换。
    • 是的。这就是为什么有人在graphql-java 之上提出另一个框架,例如github.com/leangen/graphql-spqr,以减少您关心的样板代码,但我个人还没有尝试过。
    猜你喜欢
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-12
    • 2017-09-04
    • 2016-03-06
    • 1970-01-01
    相关资源
    最近更新 更多