GraphQL HotChocolate schema-first模式实现接口抛出SchemaException问题
问题解决方案
错误原因
你遇到的报错是两个原因共同导致的:
- GraphQL规范要求:实现接口的对象类型必须显式声明接口定义的所有字段,你当前schema里的
SitesResponse只声明了items字段,漏了PagedResponse接口要求的hasNextPage/hasPreviousPage/totalCount三个字段。 - 现有配置可以支持直接返回泛型
PagedResponse<T>,不需要为每个实体单独编写响应类。
方案1:保留现有SitesResponse定义,修复配置
第一步:修正GraphQL Schema
补全SitesResponse的接口字段:
type SitesResponse implements PagedResponse { # 补全接口要求的所有字段 hasNextPage: Boolean! hasPreviousPage: Boolean! totalCount: Int! items: [Site] }
第二步:确认C#类命名匹配
默认Hot Chocolate会自动把Schema的小驼峰字段和C#类的大驼峰属性做匹配,你的PagedResponse<T>里的HasNextPage/HasPreviousPage/TotalCount属性完全符合匹配规则,现有BindRuntimeType配置不需要修改,重启即可正常运行。
方案2:复用泛型类型,避免重复定义响应类
如果不想为每个实体单独写XxxResponse类型,可以直接用Hot Chocolate支持的泛型Schema类型,大幅减少重复代码:
第一步:修改GraphQL Schema,定义通用泛型分页类型
interface PagedResponse { hasNextPage: Boolean! hasPreviousPage: Boolean! totalCount: Int! } # 定义通用泛型分页响应,无需再为每个实体单独写响应类型 type PagedResponse<T> implements PagedResponse { hasNextPage: Boolean! hasPreviousPage: Boolean! totalCount: Int! items: [T!]! } type Query { sites(skip: Int, take: Int): PagedResponse<Site> # 后续新增其他分页接口直接套用即可,比如: # users(skip: Int, take: Int): PagedResponse<User> }
第二步:简化Startup配置
删除原来的BindRuntimeType<PagedResponse<Site>>("SitesResponse")配置即可,Hot Chocolate会自动将C#的PagedResponse<Site>和Schema的PagedResponse<Site>做绑定,后续新增其他实体的分页接口也不需要额外加配置。
内容的提问来源于stack exchange,提问作者Ricky Gummadi
相关产品推荐
相关产品推荐

