tgk
tgk

Reputation: 4096

How to create nested GraphQL fields with Sangria's `@GraphQLField` annotation

I have a simple case class MyContext(queries: Query) that I provide to the schema with : sangria.schema.Schema(deriveContextObjectType[MyContext, Query, Unit](_.queries)

MyQuery is a trait of Query

trait MyQuery {
  @GraphQLField
  def item(ctx: Context[MyContext, Unit])(id: String) ... 
}

This works great. But what if I want to nest resolvers?

query { 
   item { 
     status # status is resolved from source B
     price # price is resolved from source C
   }
 }

Is that possible to achieve? Would I return an ObjectType[Item] that has properties status and price annotated with @GraphQLField?

Upvotes: 1

Views: 603

Answers (2)

tgk
tgk

Reputation: 4096

Really appreciate @tenshi's answer! I tried using the deriveObjectType but was getting a type error:

type mismatch;
 found   : sangria.schema.Context[MyContext,Item]
 required: sangria.schema.Context[MyContext,Unit]

But using deriveContextObjectType in conjunction with AddFields is working:

def schema = sangria.schema.Schema(
    deriveContextObjectType[MyContext, Query, Unit](_.queries,
      AddFields(
        Field(
          name = "item",
          fieldType = deriveContextObjectType[MyContext, Item, Unit](_ => new Item),
          resolve = _ => ()
        )
      ))
    )

And the Schema looks good, yielding:

type Query {
  item: Item!
}

Upvotes: 1

tenshi
tenshi

Reputation: 26576

I think you can use deriveObjectType for an Item. It is also able to handle the @GraphQLField annotation (as an alternative you can also use IncludeMethods macro setting). Here is an example:

implicit val ItemType = deriveObjectType[MyContext, Item]()

Upvotes: 1

Related Questions