3

我正在使用这个端点:

 @PostMapping("graphql")
    public ResponseEntity<Object> getResource(@RequestBody Object query) { // String query
        ExecutionResult result;
        if (query instanceof String) {
            result = graphQL.execute(query.toString()); // if plain text
        } else{
            String queryString = ((HashMap) query).get("query").toString();
            Object variables = ((HashMap) query).get("variables");
            ExecutionInput input = ExecutionInput.newExecutionInput()
                    .query(queryString)
                    .variables((Map<String, Object>) variables) // "var1" -> "test1"
                    .build();

            result = graphQL.execute(input);
        }
        return new ResponseEntity<Object>(result, HttpStatus.OK);
    }

当我没有变量时,它工作正常:

query {
    getItem(dictionaryType: "test1") {
        code
        name
        description
    }
}

在此处输入图像描述

当我添加variable它开始失败时,请参见此处:

query {
    getItem(dictionaryType: $var1) {
        code
        name
        description
    }
}

在此处输入图像描述

在我的schema我定义的query部分如下:

type Query {
    getItem(dictionaryType: String): TestEntity
}

java代码中:

@Value("classpath:test.graphqls")
private Resource schemaResource;
private GraphQL graphQL;

@PostConstruct
private 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() {
        initializeFetchers();
        return RuntimeWiring.newRuntimeWiring()
                .type("Query", typeWriting -> typeWriting
                        .dataFetcher("getItem", dictionaryItemFetcher)

                )
                .build();
}

private void initializeFetchers() {
        dictionaryItemFetcher = dataFetchingEnvironment ->
                dictionaryService.getDictionaryItemsFirstAsString(dataFetchingEnvironment.getArgument("dictionaryType"));
}
4

1 回答 1

7

操作中使用的任何变量都必须声明为操作定义的一部分,如下所示:

query OptionalButRecommendedQueryName ($var1: String) {
  getItem(dictionaryType: $var1) {
    code
    name
    description
  }
}

这允许 GraphQL 根据提供的类型验证您的变量,并验证变量是否正在用于代替正确的输入。

于 2019-01-21T16:32:44.937 回答