-
Notifications
You must be signed in to change notification settings - Fork 4
Directive @default
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}")
}
Imagine that the id
field is present in almost all of our queries in the application code. In order not to write
boilerplate code, we can ask Kobby to generate a DSL in such a way that this field is automatically added to the query.
This can be done using a GraphQL directive @default
. Let's modify our schema:
directive @default on FIELD_DEFINITION
type Query {
films: [Film!]!
}
type Film {
id: ID! @default
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. If you need to exclude
the id
field from the query, use the __withoutId()
function generated by Kobby:
val context: ExampleContext = exampleContextOf(createMyAdapter())
val response = context.query {
films {
__withoutId()
title()
}
}
response.films.forEach { film ->
println("Film ${film.title}")
}
To exclude from the query all fields of type Film
, marked with the directive @default
, use the __minimize()
function:
val context: ExampleContext = exampleContextOf(createMyAdapter())
val response = context.query {
films {
__minimize()
title()
}
}
response.films.forEach { film ->
println("Film ${film.title}")
}
The __minimize()
function is automatically generated for all types defined in the schema, regardless of whether those
types have fields marked with @default
directive or not.
- The
@default
directive can only be applied to a field with no arguments. - The
@default
directive can only be applied to a field that returns a scalar or enum type. - The
@default
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!