From Hotchocolate documentation:
A resolver is a generic function that fetches data from an arbitrary data source for a particular field.
We can think of each field in our query as a method of the previous type which returns the next type.
A resolver tree is a projection of a GraphQL operation that is prepared for execution.
query { me { name company { id name } } }In Hot Chocolate, this query results in the following resolver tree.
This tree will be traversed by the execution engine, starting with one or more root resolvers. In the above example the me field represents the only root resolver.
Field resolvers that are subselections of a field, can only be executed after a value has been resolved for their parent field. In the case of the above example this means that the name and company resolvers can only run, after the me resolver has finished. Resolvers of field subselections can and will be executed in parallel.
Because of this it is important that resolvers, with the exception of top level mutation field resolvers, do not contain side-effects, since their execution order may vary.
By exploiting the Resolvers it is possible to define a schema that allows to compose the return type with all the connected types; in fact it is a question of combining JOIN between the different types required.
Our Book
in MongoDb looks like this:
{
"_id" : "75f31668-f348-4aa0-88c9-d186e0a6fe4e",
"Title" : "Reconstituirea (Reconstruction)",
"Abstract" : "Inverse",
"PublicationDate" : ISODate("2021-08-27T18:07:28.000Z"),
"Categories" : [
"Inverse"
],
"Authors" : [
"5f052310-0dff-40e7-8cc0-0a13b6d8980b",
"f01ad119-349a-4c7a-9fb8-dc0141a14397"
],
"Publisher" : "cb6807e9-dff1-4cb7-b9da-eea99c861895",
"RelatedBooks" : [
"6fed258d-b0e7-4b7c-a0bc-2890a94bc8b9",
"b562b54c-ed12-4013-ab9e-3c575e4a4819",
"f6b7de8f-1d0d-4188-aec8-f122fadbb54f"
]
}
Thanks to the resolvers it is possible to define a schema of the following type:
type Book implements Node {
id: ID!
authors: [Author!]!
publisher: Publisher
relatedBooks: [Book!]!
title: String
abstract: String
publicationDate: DateTime
categories: [String!]
}
Where authors
, publisher
and relatedBooks
are complex types and no longer string ids, respectively
This allows the GraphQL client to execute nested queries.
query {
books(first:1, where: {title: { startsWith: "Reconstituirea"}}) {
nodes {
id
title
authors {
firstName
surnName
}
relatedBooks {
title
publicationDate
relatedBooks {
title
}
}
}
}
}
At this point we understand "Graph" part of GraphQL.