Ожидаемый тип 'Upload' будет GraphQLInputType Был ли тип разрешен только для типов объектов, неправильно используемых в качестве типа ввода, или наоборот - PullRequest
0 голосов
/ 17 января 2020

Здесь я пытаюсь получить файл загрузки в Graphql. Мой код выглядит следующим образом:

Схема Graphql example.graphqls

scalar Upload
type Mutation {
    uploadFile(input: CreateFileUploadInput): Boolean
}

input CreateFileUploadInput {
    files: Upload
    id: String
}

Загрузка скаляра Graphql, определенная в GraphqlConfig.java

@Configuration
public class GraphqlConfig {

  @Bean
  public SchemaParserOptions schemaParserOptions(
          GraphQlObjectMapperConfigurer customObjectMapperConfigurer) {
    return SchemaParserOptions.newOptions().objectMapperConfigurer(customObjectMapperConfigurer)
            .build();
  }

  @Bean
  GraphQLScalarType upload() {
    return graphql.servlet.ApolloScalars.Upload;
  }
}

Конфигуратор Graphql Objectmapper GraphQlObjectMapperConfigurer.java

@Component
public class GraphQlObjectMapperConfigurer  implements ObjectMapperConfigurer {
  @Override
  public void configure(ObjectMapper mapper, ObjectMapperConfigurerContext context) {
    mapper.registerModule(new JavaTimeModule())
        .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
        .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
        .setTimeZone(TimeZone.getDefault());
  }
}

класс моей модели CreateFileUploadInput.java

@Data
@NoArgsConstructor
@AllArgsConstructor
public class CreateFileUploadInput {
  private Part files;
  private String id;
}

Я использую версию загрузки с использованием GraphQL в build.gradle, 5.8.1 и Gradle gradle-5.6.2-bin

Я получаю ниже Исключение, пока я запускаю свое приложение Spring Boot!

2020-01-17 15:20:24.618  WARN 37316 --- [           main] c.c.graphql.tools.SchemaClassScanner     : Cannot find definition for field 'files: Upload' on input type 'CreateFileUploadInput' -> javax.servlet.http.Part. Try adding it manually to the dictionary
2020-01-17 15:20:24.665  WARN 37316 --- [           main] c.c.graphql.tools.SchemaClassScanner     : Schema type was defined but can never be accessed, and can be safely deleted: Upload
2020-01-17 15:20:24.665  WARN 37316 --- [           main] c.c.graphql.tools.SchemaClassScanner     : Schema type was defined but can never be accessed, and can be safely deleted: PageInfo
2020-01-17 15:20:24.752 ERROR 37316 --- [           main] o.s.b.web.embedded.tomcat.TomcatStarter  : Error starting Tomcat context. Exception: org.springframework.beans.factory.UnsatisfiedDependencyException. Message: Error creating bean with name 'graphQLServletRegistrationBean' defined in class path resource [com/oembedler/moon/graphql/boot/GraphQLWebAutoConfiguration.class]: Unsatisfied dependency expressed through method 'graphQLServletRegistrationBean' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'graphQLHttpServlet' defined in class path resource [com/oembedler/moon/graphql/boot/GraphQLWebAutoConfiguration.class]: Unsatisfied dependency expressed through method 'graphQLHttpServlet' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'graphQLServletConfiguration' defined in class path resource [com/oembedler/moon/graphql/boot/GraphQLWebAutoConfiguration.class]: Unsatisfied dependency expressed through method 'graphQLServletConfiguration' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'invocationInputFactory' defined in class path resource [com/oembedler/moon/graphql/boot/GraphQLWebAutoConfiguration.class]: Unsatisfied dependency expressed through method 'invocationInputFactory' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'graphQLSchemaProvider' defined in class path resource [com/oembedler/moon/graphql/boot/GraphQLWebAutoConfiguration.class]: Unsatisfied dependency expressed through method 'graphQLSchemaProvider' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'graphQLSchema' defined in class path resource [com/oembedler/moon/graphql/boot/GraphQLJavaToolsAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [graphql.schema.GraphQLSchema]: Factory method 'graphQLSchema' threw exception; nested exception is com.coxautodev.graphql.tools.SchemaError: Expected type 'Upload' to be a GraphQLInputType, but it wasn't!  Was a type only permitted for object types incorrectly used as an input type, or vice-versa?
2020-01-17 15:20:24.789  INFO 37316 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2020-01-17 15:20:24.794  WARN 37316 --- [           main] o.a.c.loader.WebappClassLoaderBase       : The web application [ROOT] appears to have started a thread named [HikariPool-1 housekeeper] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 sun.misc.Unsafe.park(Native Method)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [graphql.schema.GraphQLSchema]: Factory method 'graphQLSchema' threw exception; nested exception is com.coxautodev.graphql.tools.SchemaError: Expected type 'Upload' to be a GraphQLInputType, but it wasn't!  Was a type only permitted for object types incorrectly used as an input type, or vice-versa?
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:622) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    ... 128 common frames omitted
Caused by: com.coxautodev.graphql.tools.SchemaError: Expected type 'Upload' to be a GraphQLInputType, but it wasn't!  Was a type only permitted for object types incorrectly used as an input type, or vice-versa?
    at com.coxautodev.graphql.tools.SchemaParser.determineType(SchemaParser.kt:350) ~[graphql-java-tools-5.6.0.jar:na]

Я тратил много раз, чтобы исследовать эту проблему, но я не смог ее решить. Пожалуйста, помогите!

1 Ответ

0 голосов
/ 11 марта 2020

У меня была такая же проблема здесь, и я смог ее решить (пусть не очень хорошим способом) после прочтения чего-то, упомянутого в https://github.com/graphql-java-kickstart/graphql-java-tools/issues/77.

В нем говорится что при использовании типа явно в root запроса / мутации он также будет доступен на вложенном уровне. В вашем случае это будет означать добавление к вашему определению дополнительного метода, например typLoaderDummy, как показано в примере ниже (который фактически не будет использоваться). Имейте в виду, что вам нужно будет предоставить реализацию для этого "фиктивного" метода в вашей реализации Java.

scalar Upload
type Mutation {
    uploadFile(input: CreateFileUploadInput): Boolean
    typeLoaderDummy(upload: Upload): Boolean
}

Для меня этот обходной путь решил проблему.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...