Kotlin extensions for GraphQL

65 views Asked by At

We are stuck using an old version of Netflix DGS for GraphQL. It lets us write a schema and generates Java classes. A query looks something like this:

FooProjectionRoot()
  .bar()
  .baz()
  .parent()
  .yolo()

where the GraphQL structure was something like

type Bar {
  baz: String
}

type Foo {
  bar: Bar
  yolo: Int
}

Now we would like to use the Kotlin DSL to write queries like this instead:

FooProjectionRoot {
  bar {
    baz
  }
  yolo
}

We wrote an extension function and got close, but still have this helper function g that should disappear. Now queries look like this:

fun <T : BaseProjectionNode> T.g(initializer: T.() -> Unit): T {
    return this.apply(initializer)
}

FooProjectionRoot().g {
  bar().g {
    baz()
  }
  yolo()
}

The generated code for any type looks something like this:

class Foo : BaseProjectionNode {
  fun bar() {
    val bar = Bar()
    // add bar to output
    return bar
  }

  fun yolo() {
    // add yolo to output
    return this
  }
}

So every attribute has a method that either returns this or the next lower level. I would love to add a new method for each existing method that takes the init block as a parameter, calls the original method and then applies the init block. Is something like this possible?

0

There are 0 answers