Search code examples
bazel

Using GraphQL in Bazel


There's a Gradle Plugin for GraphQL that one can easily integrate in Gradle Projects. As we are moving away from Gradle to Bazel, I am not sure how to migrate a specific module that currently makes use of the Apollo Gradle Plugin.

So imagine that in Gradle the current setup is like this:

plugins {
    // ...
    id("com.apollographql.apollo3").version("3.6.2")
}


apollo {
    packageName.set("com.example.rocketreserver")
    srcDir("/src/main/java/com/example/rocketreserver/graphql")
}

How would one go about converting this to Bazel?

Is it possible, somehow, to generate a wrapper (maybe custom rule?) on top of the original plugin and use it in Bazel, or a new plugin from scratch should be written in this case?

Any input is highly appreciated.


Solution

  • There's no Bazel equivalent for the Apollo Gradle plugin, however, building one for Bazel is pretty straightforward.

    How the Gradle Apollo plugin works

    If we check the sources of the Apollo Gradle plugin, we notice that the gradle plugin is nothing but a facade in front of the apollo-compiler library. apollo-compiler is a separate library responsible for the actual code generation, and this library is decoupled from the gradle plugin implementation.

    To trigger code generation directly via apollo-compiler one can use:

    import java.io.File
    
    val outputDir = File("apollo")
    val queryFile = File("queries.graphql")
    val schemaFile = File("schema.graphqls")
    val testDir = File("apolloTest")
    val packageName = "com.example"
    
    val options = Options(
        setOf(queryFile),
        schemaFile,
        outputDir,
        testDir,
        packageName
    )
    
    ApolloCompiler.write(options)
    

    The generated sources will be placed in a directory defined by outputDir in a package defined by packageName.

    Building a Bazel rule that triggers the code generation

    With the above in place we can now create a Bazel rule that takes as input the schema and .graphql files and produces as output the generated source code. For convenience, the generated source code is zipped into a source jar, and this source jar becomes the target's output which other rules can depend on.