如何将参数/变量传递给查询或突变



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

@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 tokenn 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请求?预先感谢。

您实际上并未将变量传递给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中发现了一个物体,那里有一个琴弦。不确定它是在哪里组成的,但我怀疑网络部件比实际代码更多。

无论哪种方式,请在控制器代码内放置一个断点,看看是否正确启动请求以及是否完全击中了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();
}

to

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();
}

由于其他线是多余的。他们只是设置已经默认行为。

您可以将VTL用于此USECase

Map<String, Object> requestBody = new HashMap<>();
        String query = "query MyQuery {"
                + "    getTemplate("
                + "        id: "$id""
                + "    ){"
                + "        id"
                + "        listOfPlaceholders"
                + "        messageTemplate"
                + "        type"
                + "    }"
                + "}";
        VelocityContext queryContext = new VelocityContext();
        queryContext.put("id", data.get("id"));
        StringWriter queryWriter = new StringWriter();
        Velocity.evaluate(context, queryWriter, "TemplateName", query);
        System.out.println(queryWriter.toString());
        requestBody.put("query", queryWriter.toString());

相关内容

  • 没有找到相关文章

最新更新