GraphQL
Directives
Put a rule or behaviour on a field, right in the schema.
A directive is an annotation in the schema that changes how a field behaves, written with @. You have already seen one: @deprecated. You can make your own: this field is upper-cased, this field needs the admin role, this field is cached.
directive @upper on FIELD_DEFINITION
directive @auth(role: String!) on FIELD_DEFINITION
type Query {
greeting: String @upper
secrets: [String!]! @auth(role: "admin")
}You declare the directive in the schema (its name, arguments and where it may be used), use it on fields, and implement it once in Kotlin:
useGraphQL {
schema = SDL
directive("upper") { _, _, next -> (next() as String).uppercase() }
directive("auth") { args, env, next ->
val http = env.graphQlContext.get<HttpContext>("kest.http") // the HTTP request this query came in on
val user = http?.principal ?: throw UnauthorizedException("Sign in first")
if (args["role"] !in user.roles) throw ForbiddenException("Needs the ${args["role"]} role")
next() // run the field's own resolver
}
}The handler receives:
args | the arguments written where the directive is used (@auth(role: "admin") gives {role: "admin"}) |
env | the DataFetchingEnvironment: the field, its arguments, the parent object, the request context |
next | a function that runs the field's own resolver. Not calling it skips the resolver; changing its result changes the response |
Loading diagram…
Directive or guard?
| Use a directive when | Use a guard (@Authenticated, @Roles) when |
|---|---|
the rule belongs to the schema: every client reading introspection sees @auth(role: "admin") | the rule belongs to the resolver method |
| the same rule applies to fields of several types, chosen in the SDL | you want the same annotations as on REST controllers |
| it changes the value (formatting, masking, caching) | it only allows or refuses |
@deprecated(reason: "...") is built into GraphQL and needs no code.