Skip to content

Directive @primaryKey

dermakov edited this page Aug 18, 2021 · 3 revisions

The @required 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 @primaryKey directive does the same, but additionally generates equals and hashCode functions for entities by all fields marked with this directive. You cannot exclude a 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 and generate the equals and hashCode functions for the Film entity using the id field, we must mark this field with the @primaryKey directive. Let's modify our schema:

directive @primaryKey on FIELD_DEFINITION

type Query {
    films: [Film!]!
}

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

Clone this wiki locally