GraphQL
Resolvers
The classes that answer your schema's fields, declared like controllers.
A resolver is a class marked @Resolver. Each method answers one field of your schema. It is declared just like an HTTP controller: no @Injectable, listed under the module's controllers, and it can take any provider in its constructor:
@Resolver
class OrderResolver(private val orders: OrderService) {
@Query fun order(id: String): Order? = orders.find(id) // Query.order(id: ID!)
@Query("myOrders") fun mine(status: String?): List<Order> = ... // the field name can differ from the method name
@Mutation fun cancel(id: String): Order = orders.cancel(id) // Mutation.cancel
@ResolveField("Order") fun customer(order: Order): Customer = ... // Order.customer
}
@Module(controllers = [OrderController::class, OrderResolver::class]) // REST and GraphQL entry points together
class OrdersModule| Annotation | Answers |
|---|---|
@Query | a field of type Query |
@Mutation | a field of type Mutation |
@Subscription | a field of type Subscription (returns a stream) |
@ResolveField("Type") | a field of any other type, computed when asked for |
@BatchLoader("name") | a batched lookup, see Data loaders |
Arguments
Method parameters bind by name to the field's arguments, and are decoded with the application's JSON codec, so they can be numbers, enums, lists, or your own classes (input types):
input OrderFilter { status: String minTotal: Int }
type Query { orders(filter: OrderFilter, limit: Int): [Order!]! }data class OrderFilter(val status: String?, val minTotal: Int?)
@Query fun orders(filter: OrderFilter?, limit: Int?): List<Order> = orders.search(filter, limit ?: 20)A parameter whose type is nullable (Int?) is optional. A handler may also take the DataFetchingEnvironment (to read the selection set or the request) and, for @ResolveField, the parent object as the first parameter.
Field resolvers: do work only when asked
@ResolveField("Order") fun customer(order: Order) runs only when a query selects customer, once per order in the result. That is great for things that cost something (a database call), and the reason to use data loaders when the result is a list.
Security
@Authenticated, @Roles, @Role, @Public and your own guards behave exactly as on controllers (see Authorization). They run before the resolver method, for queries, mutations, fields and subscriptions, on the class or on single methods:
@Resolver @Authenticated // every field of this resolver needs a login
class AdminResolver {
@Query fun users(): List<User> = ...
@Public @Query fun teaser(): String = "..." // except this one
@Roles("admin") @Mutation fun purge(): Boolean = ... // and this one also needs a role
}The GraphQL endpoint itself skips the global guards by default (some fields are public). Set applyGlobalGuards = true to protect the whole endpoint, or guard individual resolvers. Remember that authorization belongs on the data, not the entry point: a { user(id) { email } } field must check who is asking, even if the query is "authenticated".
Errors
An exception in a resolver does not fail the whole response. GraphQL returns what it could, plus an errors entry:
{ "data": { "order": null }, "errors": [{ "message": "Order 9 not found", "path": ["order"], "extensions": { "code": "NOT_FOUND", "status": 404 } }] }| Your code throws | Client sees extensions.code |
|---|---|
UnauthorizedException (401) | UNAUTHENTICATED |
ForbiddenException (403) | FORBIDDEN |
BadRequestException, validation (400, 422) | BAD_USER_INPUT (with details) |
NotFoundException | NOT_FOUND |
ConflictException | CONFLICT |
| anything else | INTERNAL_SERVER_ERROR, with the generic message "Internal server error": the real cause is logged and sent to error monitoring, never to the client |
Throw the same HTTP exceptions you use in controllers; they are translated. A field declared non-null (String!) that fails makes its parent null, and so on upward, so declare fields nullable when failure is normal.
Testing
Post a query to the endpoint with the test server and assert the JSON, or call the resolver class directly: it is a plain class with plain methods.