使用grapiql的GraphQl变量 - 变量未定义

try*_*ard 2 java graphql graphql-java graphiql

我正在使用这个端点:

 @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);
    }
Run Code Online (Sandbox Code Playgroud)

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

query {
    getItem(dictionaryType: "test1") {
        code
        name
        description
    }
}
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

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

query {
    getItem(dictionaryType: $var1) {
        code
        name
        description
    }
}
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

在我schemaquery部分中,我定义了如下部分:

type Query {
    getItem(dictionaryType: String): TestEntity
}
Run Code Online (Sandbox Code Playgroud)

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"));
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*den 5

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

query OptionalButRecommendedQueryName ($var1: String) {
  getItem(dictionaryType: $var1) {
    code
    name
    description
  }
}
Run Code Online (Sandbox Code Playgroud)

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