Skip to content

Directive @default

dermakov edited this page Aug 17, 2021 · 5 revisions

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()
    }
}

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 request. 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()
    }
}

The generated DSL will automatically add the id field to FilmProjection. If you need to exclude the id field from the request, use the __withoutId() function generated by Kobby:

val context: ExampleContext = exampleContextOf(createMyAdapter())
val response = context.query {
    films {
        __withoutId()
        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()
    }
}

Clone this wiki locally