Skip to content

Directive @required

dermakov edited this page Aug 18, 2021 · 2 revisions

The @default directive provides the ability to generate a DSL in such a way that the field marked with this directive is automatically added to the query. The @required directive does the same, but does not allow excluding the field marked with this directive from the query. Kobby does not generate __withoutXXX() methods for fields marked with such a directive, and does not allow such fields to be excluded using the __minimize() function. Let define a GraphQL schema:

type Query {
    films: Film!
}

type Film {
    id: ID!
    title: String!
}

This schema allows us to write a query using the generated DSL that looks like this:

val context: ExampleContext = exampleContextOf(createMyAdapter())
val response = context.query {
    films {
        id()
        title()
    }
}

response.films.forEach { film ->
    println("Film ${film.id} ${film.title}")
}

If we want to generate a DSL that will automatically include the id field in the query, we must mark this field with the @required directive. Let's modify our schema:

directive @required on FIELD_DEFINITION

type Query {
    films: [Film!]!
}

type Film {
    id: ID! @required
    title: String!
}

Now we can write our query like this:

val context: ExampleContext = exampleContextOf(createMyAdapter())
val response = context.query {
    films {
        title()
    }
}

response.films.forEach { film ->
    println("Film ${film.id} ${film.title}")
}

The generated DSL will automatically add the id field to the projection of the Film query.

Restrictions

  • The @required directive can only be applied to a field with no arguments.
  • The @required directive can only be applied to a field that returns a scalar or enum type.
  • The @required directive cannot be applied to overridden fields. In this case, apply the directive to the base interface field.

In case of violation of any restriction, the directive will be ignored.

In case of a field is marked with several directives at once - @default, @required, @primaryKey, the behavior of the Kobby Plugin is undefined!