Page类的graphql模式定义应该是什么样的?

时间:2018-11-25 22:22:29

标签: kotlin spring-data graphql graphql-java

所以我在科特林有这堂课:

@Component
class UserResolver @Autowired
constructor(private val userService: UserService): GraphQLMutationResolver, GraphQLQueryResolver {

    fun createUser(user: User): User {
        userService.save(user)
        return user
    }

    fun users(): Page<User> {
        val pageable = QPageRequest(0, 10)

        return userService.all(pageable)
    }
}

我希望方法用户返回Page对象,这对graphql是完全陌生的。我尝试过这样的事情:

type Page {
    number: Int
    size: Int
    numberOfElements: Int
    content: []
    hasContent: Boolean
    isFirst: Boolean
    isLast: Boolean
    hasNext: Boolean
    hasPrevoius: Boolean
    totalPages: Int
    totalElements: Float
}

但是我的Spring Boot应用程序无法启动,我不知道此类https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/domain/Page.html的架构定义应该是什么样。有人有主意吗?

修改:错误是:

  

通过工厂方法实例化Bean失败;嵌套异常为   org.springframework.beans.BeanInstantiationException:失败   实例化[com.coxautodev.graphql.tools.SchemaParser]:工厂   方法“ schemaParser”抛出异常;嵌套异常为   com.coxautodev.graphql.tools.TypeClassMatcher $ RawClassRequiredForGraphQLMappingException:   类型   org.springframework.data.domain.Page 无法映射到GraphQL类型!由于GraphQL-Java交易   在运行时使用擦除类型,只有非参数化类可以   代表GraphQL类型。这允许通过Java进行反向查找   接口和联合类型中的类。

1 个答案:

答案 0 :(得分:2)

在过去的几个月中,使用GraphQL Java工具对泛型的处理已发生了一些变化。您使用什么版本?我只是在5.4.1版中尝试过,它似乎可以工作,尽管在5.2.4中却没有。我不知道是否可以解决this问题。

以防万一,这是我使用的测试内容:

首先,我声明了一个这样的类:class Page<T>(val number: Int, val size: Int)

第二,在解析器中,我有fun users() = Page<User>(...)

第三,在GraphQL模式文件中,我有这个

type Page {
    number: Int
    size: Int!
}

type Query {
    users: Page
}

上述限制是您在GraphQL模式中只有一个类型,简称为Page。但是想必您想了解有关User对象的特定信息吗?这是否意味着在您的示例中的content属性中?如果是这样,我认为您需要在GraphQL模式中为可能传递给Page的通用类型参数的每种类型声明一个单独的类型,例如UserPageCustomerPage等。然后,在代码中,每个代码都需要映射到正确的Kotlin类,例如Page<User>Page<Customer>。我不知道在没有每个泛型的具体实现的情况下在代码中执行此操作的方法(希望其他人可以解释如何执行此操作)。如果GraphQL类型名称具有相同的名称,则默认情况下它们会与Kotlin类名称结婚,或者在使用Schema

构建SchemaParser.newParser().dictionary(...时使用显式提供的映射

因此,如果您乐意为提供给它的每种类型创建泛型类的具体子类,则可以执行以下操作:

open class Page<T>(val number: Int, val size: Int, val content: List<T>)

class UserPage(number: Int, size: Int, content: List<User>): Page<User>(number, size, content)

fun users(): UserPage {...

在GraphQL模式中,您将拥有以下内容:

type UserPage {
    number: Int!
    size: Int!
    content: [User]!
}

type Query {
    users: UserPage
}
相关问题