1

我正在尝试读取通过后端变量传递的一些参数,让我们看看:(这个方法在里面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 请求?提前致谢。

4

1 回答 1

4

您实际上并没有将变量传递给 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();
}

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

于 2019-07-31T21:43:22.517 回答