Skip to content

Add an ability to generate DataFetcherResult for a specific fields in Java #1416

@kirill071992

Description

@kirill071992

Is your feature request related to a problem? Please describe.
We have some cases when local context is required for Data fetching, to be able to pass some specific data for child resolvers. In this case, global context from DataFetchingEnvironment is not an option.

An example of using a local context:

return DataFetcherResult.<MobileLandingBlockGraph>newResult()
                .data(new BooksMobileLandingBlockGQL(groups.stream()
                        .map((Function<BooksProductGroup, BooksProductGroupGraph>) BooksProductGroupGQL::new)
                        .toList()))
                .localContext(booksProductService.populateContextForMobile(input.getInput(), "advantures"))
                .build();

As DataFetcherResult is not supported in the current version of the generator, we have to use the following to be able to generate it for a specific field in GraphQl schema:

abstract class GraphQLCodegenFixesGradleTask : DefaultTask() {
    @get:InputFile
    abstract val inputFile: RegularFileProperty

    @TaskAction
    fun updateMobileLandingGridDataGraph() {
        val findStr = "java.util.List<MobileLandingBlockGraph>" // Specify the string to find
        val replaceStr = "java.util.List<graphql.execution.DataFetcherResult<MobileLandingBlockGraph>>" // Specify the string to replace with

        val file = inputFile.get().asFile
        val content = file.readText()
        val updatedContent = content.replace(findStr, replaceStr)
        file.writeText(updatedContent)
    }
}

tasks.register<GraphQLCodegenFixesGradleTask>("graphQLCodegenFixes") {
    dependsOn("graphqlCodegen")
    inputFile.set(file("$buildDir/generated/com/scentbird/web/graphql/model/MobileLandingGridDataGraph.java"))
}

Describe the solution you'd like
The solution I'm proposing is the following:

  1. Add a new property for a plugin:
    fieldsWithDataFetcherResult = setOf("@dataFetcherResult")

This property will be used to mark fields that require DataFetcherResult generation. For example:

type MobileLandingGridData {
  # blocks of landing grid
  blocks: [MobileLandingBlock!]! @dataFetcherResult
  # there are more blocks on the next page
  hasNext: Boolean!
}
  1. Update the generator to be able to generate this code.

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions