如何传递参数/变量进行查询或变异?

时间:2019-07-29 18:36:32

标签: java graphql-spqr

我正在尝试读取一些通过后端变量传递的参数,让我们看看: (此方法在AuthenticationService内部,注入到我的graphql控制器中,请参见下面的内容)

@GraphQLMutation(name = "getSessionToken")
public AuthReturn getSessionToken(@GraphQLArgument(name = "user") String u, @GraphQLArgument(name = "password") String p) {...}

这是我的graphQL请求:

mutation ($user: String!, $password: String!) {
  getSessionToken(user: $user, password: $password) {
    status
    payload
  }
}

和我的变量:

{ "user": "myuser", "password": "mypass"}

但是当我尝试运行此示例代码时,显示以下错误:

{"timestamp":"2019-07-29T17:18:32.753+0000","status":400,"error":"Bad Request","message":"JSON parse error: Cannot deserialize instance of `java.lang.String` out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.lang.String` out of START_OBJECT token\n at [Source: (PushbackInputStream); line: 1, column: 162] (through reference chain: java.util.LinkedHashMap[\"variables\"])","path":"/graphql"}

[编辑] 这是我的控制器:

@RestController
public class GraphQLController {

    private final GraphQL graphQL;

    public GraphQLController(AgendamentoService agendamentos, ConfiguracaoService config, ProcessoService processos, ParametroService parametros, AuthenticationService autenticacao) {
        GraphQLSchema schema = new GraphQLSchemaGenerator()
                .withResolverBuilders(
                        //Resolve by annotations
                        new AnnotatedResolverBuilder())
                .withOperationsFromSingletons(agendamentos, config, processos, parametros, autenticacao)
                .withValueMapperFactory(new JacksonValueMapperFactory())
                .generate();
        graphQL = GraphQL.newGraphQL(schema).build();
    }

    @CrossOrigin
    @PostMapping(value = "/graphql", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Map<String, Object> graphql(@RequestBody Map<String, String> request, HttpServletRequest raw) {
        // em context estamos passando o Request, usamos para fazer as verificacoes de autenticacao com GraphQl 
        ExecutionResult executionResult = graphQL.execute(ExecutionInput.newExecutionInput()
                .query(request.get("query"))
                .operationName(request.get("operationName"))
                .context(raw)
                .build());
        return executionResult.toSpecification();
    }
}

但是,如果我运行此突变而未根据请求将参数作为variables传递,则一切正常。如何将变量传递到graphQl请求?预先感谢。

1 个答案:

答案 0 :(得分:1)

您实际上并没有将变量传递给graphql-java。这必须通过ExecutionInput完成。 我建议创建一个类,例如:

@JsonIgnoreProperties(ignoreUnknown = true)
public class GraphQLRequest {

    private final String query;
    private final String operationName;
    private final Map<String, Object> variables;

    @JsonCreator
    public GraphQLRequest(@JsonProperty("query") String query,
                          @JsonProperty("operationName") String operationName,
                          @JsonProperty("variables") Map<String, Object> variables) {
        this.query = query;
        this.operationName = operationName;
        this.variables = variables != null ? variables : Collections.emptyMap();
    }

    public String getQuery() {
        return query;
    }

    public String getOperationName() {
        return operationName;
    }

    public Map<String, Object> getVariables() {
        return variables;
    }
}

并将其用作控制器方法中的参数:

@CrossOrigin
@PostMapping(value = "/graphql", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public Map<String, Object> graphql(@RequestBody GraphQLRequest graphQLRequest, HttpServletRequest httpRequest) {
    // em context estamos passando o Request, usamos para fazer as verificacoes de autenticacao com GraphQl 
    ExecutionInput.Builder inputBuilder = ExecutionInput.newExecutionInput()
                .query(graphQLRequest.getQuery())
                .operationName(graphQLRequest.getOperationName())
                .variables(graphQLRequest.getVariables()) //this is the line you were missing
                .context(httpRequest);
    return executionResult.toSpecification();
}

ExecutionInput中缺少变量仍然无法解释您遇到的反序列化错误。它说在JSON中找到了需要字符串的对象。不知道从哪儿来的,但是我怀疑Web部件比实际代码更多。

无论哪种方式,都在控制器代码中放置一个断点,以查看请求是否正确反序列化,以及GraphQL引擎是否被命中。

我还建议您简化设置:

public GraphQLController(AgendamentoService agendamentos, ConfiguracaoService config, ProcessoService processos, ParametroService parametros, AuthenticationService autenticacao) {
    GraphQLSchema schema = new GraphQLSchemaGenerator()
            .withResolverBuilders(
                    //Resolve by annotations
                    new AnnotatedResolverBuilder())
            .withOperationsFromSingletons(agendamentos, config, processos, parametros, autenticacao)
            .withValueMapperFactory(new JacksonValueMapperFactory())
            .generate();
    graphQL = GraphQL.newGraphQL(schema).build();
}

public GraphQLController(AgendamentoService agendamentos, ConfiguracaoService config, ProcessoService processos, ParametroService parametros, AuthenticationService autenticacao) {
    GraphQLSchema schema = new GraphQLSchemaGenerator()
            .withOperationsFromSingletons(agendamentos, config, processos, parametros, autenticacao)
            .generate();
    graphQL = GraphQL.newGraphQL(schema).build();
}

,因为其他行是多余的。他们只是在设置已经存在的默认行为。

相关问题