Why do you need and how to use viewer
correctly in Relay.js?
I've spent past week to try and understand Relay.js. Im now good with GraphQL and I understand it pretty well but Im having some issues with uniting GraphQL and Relay.js in same application.
First step would probably be to understand viewer
. I've seen many examples and tutorials using it but it's never explained and it's not very clear what is it exactly and what it is used for.
Relay documentation mentions viewer
few times but there's not even a single word explaining it.
I wish I could something more to this question but Im afraid there's no explanations online. It's only used in codes and ripping it out of context wouldn't make any sense. Answering this question will require some knowledge about Realy.js/GraphQL anyway.
My best guess based of countless examples I've examined is that it's somehow related to user? If user is anonymous or logged in? To grant different access to data based on login status or user level?
viewer
is not something Relay-specific. It's just a field name. You're rihgt. That field usually represents a GraphQLObject type for the user or viewer of the application.
The root query type is the GraphQL object that we define and pass as query
in the schema object. For instance, in the todo example application, it's Root
.
export const schema = new GraphQLSchema({
query: Root,
mutation: Mutation,
});
In the relay-treasurehunt example application, the root query type is queryType
.
export const schema = new GraphQLSchema({
query: queryType,
mutation: mutationType,
});
The root query type is the primary access point through which the other data are accessed. These other data are listed as fields of the root query object. Like any GraphQL object, the root query type can have one or more fields. In the todo example application, it has one field named viewer
:
const Root = new GraphQLObjectType({
name: 'Root',
fields: {
viewer: {
type: GraphQLUser,
resolve: () => getViewer(),
},
node: nodeField,
},
});
In the relay-treasurehunt example application, the root query type has one field named game
.
const queryType = new GraphQLObjectType({
name: 'Query',
fields: () => ({
node: nodeField,
game: {
type: gameType,
resolve: () => getGame(),
},
}),
});
Now if there is a viewer
field to represent application user or website viewer, whether the user is anonymous or logged in entirely depends on the application. If the user needs to log in, you can implement a mutation for login. You can also restrict access to data. Jonas Helfer posted an excellent answer to how user-access check can be done on the server-side.
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