aPureBase / KGraphQL

Pure Kotlin GraphQL implementation
https://kgraphql.io
MIT License
298 stars 58 forks source link

Cannot define schema outside of install with Ktor ("schemaBlock has not been initialized") #121

Closed bennettdams closed 3 years ago

bennettdams commented 3 years ago

When using KGraphQL with Ktor, I would like to define a schema outside of the main Application.kt.

An example from the docs:

fun Application.module() {
  install(GraphQL) {
    playground = true 
    schema {
      query("hello") {
        resolver { -> "World!" }
      }
    }
  }
}

You cannot skip the install(...) step and schema is required here. How would one define a schema outside of the install and use it there?

I tried the obvious with val mySchema = KGraphQL.schema { ... } and using it as schema:

fun Application.module() {
  install(GraphQL) {
    playground = true 
    mySchema
  }
}

..but this prevents the server from starting with the following error: Caused by: kotlin.UninitializedPropertyAccessException: lateinit property schemaBlock has not been initialized

jeggy commented 3 years ago

The recommended way of writing a big schema across multiples files would be extension functions.

Something like this:

fun Application.module() {
  install(GraphQL) {
    playground = true
    schema {
      mySchema()
      // You can call as many as you want here.
    }
  }
}

fun SchemaBuilder.mySchema() {
  query("hello") {
    resolver { -> "World!" }
  }
}

And when using this pattern you can ofcourse nest these, so you can again call another extension function within mySchema if needed.

bennettdams commented 3 years ago

Thanks! If you ask me, a repo with a general real world example (e.g. together with authentication) for the Ktor plugin would be really helpful.

jeggy commented 3 years ago

You can find one great recent example here: https://github.com/MattLangsenkamp/TodoTree