Resolvers Flashcards
How does our Catstronauts client send queries to our GraphQL server?
As strings using HTTP POST or GET requests
!There is no GraphQL-specific networking protocol
What are the actions that our GraphQL server takes when it receives a request?
When the server receives the HTTP request (POST or GET), it first extracts the string with the GraphQL query.
It parses and transforms it into something it can better manipulate: a tree-structured document called an AST (Abstract Syntax Tree).
With this AST, the server validates the query against the types and fields in our schema.
If anything is off (e.g. a requested field is not defined in the schema or the query is malformed), the server throws an error and sends it right back to the app.
What are the actions that our GraphQL server takes when it receives a request?
When the server receives the HTTP request (POST or GET), it first extracts the string with the GraphQL query.
It parses and transforms it into something it can better manipulate: a tree-structured document called an AST (Abstract Syntax Tree).
With this AST, the server validates the query against the types and fields in our schema.
If anything is off (e.g. a requested field is not defined in the schema or the query is malformed), the server throws an error and sends it right back to the app.
If the query looks good the server can continue its process and actually fetch the data. The server walks down the AST.
For each field in the query, the server invokes that field’s resolver function. A resolver function’s mission is to “resolve” its field by populating it with the correct data from the correct source, such as a database or a REST API.
As all of the query’s fields are resolved, the data is assembled into a nicely ordered JSON object with the exact same shape as the query.
The server assigns the object to the HTTP response body’s data key, and it’s time for the return trip, back to our app.
Which are the responsabilities of a resolver function?
Populating its corresponding field with data
Retrieving the correct data from a source such as a database or a REST API
From where a resolver can retrieve data?
From data sources.
A data source can be of all kinds: database, third-party API, webhooks and so on.
With GraphQL, one query is often composed of a mix of different fields and types, coming from different endpoints, with different cache policies. So how should we deal with caching in this context?
Using RESTDataSource
It helps manage the mix of different endpoints with different cache policies
It helps resolve query fields that have already been fetched much faster
It prevents unnecessary REST API calls for data that doesn’t get updated frequently
What is a resolver?
A resolver is a function. It has the same name as the field that it populates data for. It can fetch data from any data source, then transforms that data into the shape your client requires.