Skip to content

GraphQL Operations

A resolver often needs to run a subquery or submutation — a query or mutation against the root Query/Mutation type from inside the resolver. Declare it with @GraphQLOperation and pass the operation object to ctx.query() / ctx.mutation(). Both languages support this pattern, including build-time validation and reuse across resolvers. Java also provides string overloads for dynamically constructed selections; Kotlin's operation API takes operation objects.

@GraphQLOperation is annotated @StableApi in both tenant APIs.

Declaring a query operation

A GraphQL operation is annotated with @GraphQLOperation and extends QueryFromAnnotation for a query (or MutationFromAnnotation for a mutation). Kotlin uses a singleton object; Java uses a class and explicitly exposes an INSTANCE to reuse. The filmography tenant declares one that looks a character up by name and selects its identity fields through the shared CharacterIdentityFields named fragment:

@GraphQLOperation(
    """
    query(${'$'}name: String!) {
      searchCharacter(search: { byName: ${'$'}name }) {
        ...CharacterIdentityFields
      }
    }
    """
)
object CharacterByNameOperation : QueryFromAnnotation()

View full file on GitHub

package com.example.starwars.modules.filmography.characters.operations;

/** Statically validated subquery used by a Java resolver. */
@GraphQLOperation(
    """
    query($name: String!) {
      searchCharacter(search: { byName: $name }) {
        ...CharacterIdentityFields
      }
    }
    """)
public final class CharacterByNameOperation extends QueryFromAnnotation {
  public static final CharacterByNameOperation INSTANCE = new CharacterByNameOperation();

  private CharacterByNameOperation() {}
}

View full file on GitHub

The document is validated against the schema at build time: it must contain exactly one operation, its type must match the base class (query for QueryFromAnnotation), variables must line up with the fields they feed, and any ...FragmentName spread must resolve to a @GraphQLFragment declared in the same tenant module.

Running it with ctx.query()

Pass the operation object — not a string — to ctx.query(), along with a map of its variables. Viaduct inlines the external fragments the operation spreads and executes it against the root Query type, returning a typed Query GRT whose getters mirror the schema. Java returns it asynchronously in a CompletableFuture, so the consumer uses thenApply:

@Resolver
@Prototype
class CharacterSummaryByNameQueryResolver : QueryResolvers.CharacterSummaryByName() {
    override suspend fun resolve(ctx: Context): String? {
        val result = ctx.query(CharacterByNameOperation, mapOf("name" to ctx.arguments.name))
        val character = result.getSearchCharacterOrThrow() ?: return null

        val name = character.getNameOrThrow() ?: "Unknown"
        val birthYear = character.getBirthYearOrThrow() ?: "Unknown birth year"
        return "$name ($birthYear)"
    }

View full file on GitHub

package com.example.starwars.modules.filmography.characters.queries;

/** Executes a statically declared Java query operation from a resolver. */
@Resolver
@Prototype
public final class CharacterSummaryByNameQueryResolver
    extends QueryResolvers.CharacterSummaryByName {
  @Override
  public CompletableFuture<String> resolve(Context context) {
    return context
        .query(CharacterByNameOperation.INSTANCE, Map.of("name", context.getArguments().getName()))
        .thenApply(
            query -> {
              viaduct.java.grts.Character character = query.getSearchCharacter();
              if (character == null) {
                return null;
              }
              String name = character.getName() == null ? "Unknown" : character.getName();
              String birthYear =
                  character.getBirthYear() == null
                      ? "Unknown birth year"
                      : character.getBirthYear();
              return name + " (" + birthYear + ")";
            });
  }
}

View full file on GitHub

Try it in GraphiQL:

query {
  characterSummaryByName(name: "Luke")
}

Declaring and running a mutation operation

Mutations work the same way, using MutationFromAnnotation and ctx.mutation(). This operation delegates to the existing updateCharacterName mutation:

@GraphQLOperation(
    """
    mutation(${'$'}id: ID!, ${'$'}name: String!) {
      updateCharacterName(id: ${'$'}id, name: ${'$'}name) {
        ...CharacterIdentityFields
      }
    }
    """
)
object RenameCharacterOperation : MutationFromAnnotation()

View full file on GitHub

package com.example.starwars.modules.filmography.characters.operations;

/** Statically validated submutation used by a Java resolver. */
@GraphQLOperation(
    """
    mutation($id: ID!, $name: String!) {
      updateCharacterName(id: $id, name: $name) {
        ...CharacterIdentityFields
      }
    }
    """)
public final class RenameCharacterOperation extends MutationFromAnnotation {
  public static final RenameCharacterOperation INSTANCE = new RenameCharacterOperation();

  private RenameCharacterOperation() {}
}

View full file on GitHub

ctx.mutation() is only available from a resolver on the root Mutation type, so the consumer backs a Mutation field. The submutation shares the parent request's state — including the admin security context — so the updateCharacterName resolver it delegates to is still access-checked:

@Resolver
@Prototype
class RenameCharacterSummaryMutation : MutationResolvers.RenameCharacterSummary() {
    override suspend fun resolve(ctx: Context): String? {
        val result = ctx.mutation(
            RenameCharacterOperation,
            mapOf(
                "id" to ctx.arguments.id,
                "name" to ctx.arguments.name
            )
        )
        val character = result.getUpdateCharacterNameOrThrow() ?: return null

        val name = character.getNameOrThrow() ?: "Unknown"
        val birthYear = character.getBirthYearOrThrow() ?: "Unknown birth year"
        return "$name ($birthYear)"
    }

View full file on GitHub

package com.example.starwars.modules.filmography.characters.mutations;

/** Executes a statically declared Java mutation operation from a resolver. */
@Resolver
@Prototype
public final class RenameCharacterSummaryMutation extends MutationResolvers.RenameCharacterSummary {
  @Override
  public CompletableFuture<String> resolve(Context context) {
    return context
        .mutation(
            RenameCharacterOperation.INSTANCE,
            Map.of(
                "id", context.getArguments().getId(),
                "name", context.getArguments().getName()))
        .thenApply(
            mutation -> {
              viaduct.java.grts.Character character = mutation.getUpdateCharacterName();
              if (character == null) {
                return null;
              }
              String name = character.getName() == null ? "Unknown" : character.getName();
              String birthYear =
                  character.getBirthYear() == null
                      ? "Unknown birth year"
                      : character.getBirthYear();
              return name + " (" + birthYear + ")";
            });
  }
}

View full file on GitHub

Run it with the security-access: admin header set (see Request Context):

mutation {
  renameCharacterSummary(id: "Q2hhcmFjdGVyOjE=", name: "Ben Kenobi")
}

When to reach for @GraphQLOperation

Use a declared operation when the selection is fixed (known at build time) and you want it validated against the schema, reused across resolvers, or simply kept out of the resolver body. Java's string overloads can handle selections constructed at runtime; these are not Kotlin overloads. If the parent object or root Query already has the data you need before the resolver runs, prefer declaring it in the @Resolver annotation's objectValueFragment / queryValueFragment — see Subqueries for the full comparison.

For the API reference and validation rules, see the GraphQL Operations developer reference. For the fragment the operations above spread, see Named Fragments.