What is the purpose of root query field viewer
in GraphQL?
Based on this article, viewer
could be used to accept a token parameter so we can see who is currently logged in.
How should I implement it?
A field is essentially an object-specific attribute that holds a value. The object's parent type defines which fields an object must have. Each field is set at definition to hold certain data types, such as String or Enum .
GraphQL works by sending operations to an endpoint. There are three types of operations: queries, mutations, and subscriptions. A query is sent through an HTTP POST call to retrieve data.
From the point of view of the client, the most common GraphQL operations are likely to be queries and mutations.
These three dots instruct GraphQL to assign the fields from the fragment to the current selection set. This change to the selection set in the liftInfo fragment causes every query that is using this fragment to select less data. Fragments are a pretty slick feature of the GraphQL query language.
viewer
root query fieldviewer
is not something GraphQL or Relay-specific. Most web applications serve some purposes of its users or viewers. The top level entity to model the various data served to the user can be named as viewer
. You can also name it user
. For example, the Relay todo example has a viewer
root query field:
viewer: { type: GraphQLUser, resolve: () => getViewer(), },
We may also do without viewer
. For instance, Relay starwars example does not have any viewer
root query field.
In short, having this viewer
as a root query field of the GraphQL schema enables us to provide data based on the current user.
My answer follows what is already described in your mentioned article. The steps are:
On the server-side, create a mutation to obtain an authentication token. Let's name it LoginMutation
. Input to this mutation are the user credentials and the output is an authentication token.
On the client-side, if you use relay framework, implement a client-side mutation. After the mutation is successful, store the authentication token.
On the client-side Relay code, add authToken
parameter for your viewer
queries. The value of authToken
is the authentication token received after successful login mutation.
As already mentioned in the article, an alternative way of authenticating user is to do it outside of GraphQL. You may want to see two excellent answers this and this for details.
Jonas Helfer wrote a two-part article on this, which you'll find very useful: Part 1, Part 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With