想象一下,我将此作为我的架构,人们用鸟ID查询,如果他们询问位置,他们就会获得有关该位置的所有信息。我还需要以“架构”格式定义位置吗?或者有没有办法在这里立即使用案例类?
如果你想了解我为什么要这样做的背景知识: 我得到了一个大规模嵌套的JSon架构,它几乎不可能管理它的每个级别。我很高兴请求顶层元素的用户将返回在该阶段定义的案例类。
import sangria.schema._
case class Location( lat: String, long: String )
case class Bird( name: String, location: List[Location] )
class BirdRepo {
def get(id: Int ) = {
if( id < 10 ) {
Bird( "Small",
List( Location("1", "2"), Location("3", "4")
))
} else {
Bird( "Big",
List( Location("5", "6"), Location("7", "8")
))
}
}
}
object SchemaDefinition {
val Bird = ObjectType(
"Bird",
"Some Bird",
fields[BirdRepo, Bird] (
Field( "name", StringType, resolve = _.value.name ),
Field( "location", List[Location], resolve = _.value.location)
// ^^ I know this is not possible
)
)
}
答案 0 :(得分:4)
正如@Tyler所提到的,您可以使用deriveObjectType
。两种类型的定义如下所示:
implicit val LocationType = deriveObjectType[BirdRepo, Location]()
implicit val BirdType = deriveObjectType[BirdRepo, Bird]()
只要您的deriveObjectType
(在您的情况下为List[Location]
)定义了隐式实例, ObjectType[BirdRepo, Location]
就可以正确处理LocationType
在范围内。
字段(“location”,List [Location],resolve = _.value.location)
正确的语法是:
Field( "location", ListType(LocationType), resolve = _.value.location)
假设您已经在别处定义了LocationType
。
答案 1 :(得分:1)
从文档中,您应该查看ObjectType Derivation
部分以下是示例:
case class User(id: String, permissions: List[String], password: String)
val UserType = deriveObjectType[MyCtx, User](
ObjectTypeName("AuthUser"),
ObjectTypeDescription("A user of the system."),
RenameField("id", "identifier"),
DocumentField("permissions", "User permissions",
deprecationReason = Some("Will not be exposed in future")),
ExcludeFields("password"))
你会注意到你仍然需要提供名称,然后有一些可选的东西,比如重命名字段和折旧。
它将生成一个与此类似的ObjectType:
ObjectType("AuthUser", "A user of the system.", fields[MyCtx, User](
Field("identifier", StringType, resolve = _.value.id),
Field("permissions", ListType(StringType),
description = Some("User permissions"),
deprecationReason = Some("Will not be exposed in future"),
resolve = _.value.permissions)))