I was watching a youtube video by Dan Schafer of Facebook where he talks about a lot of things, with the immedate take-away for me of rooting the graphql query in the current viewer or user of the website (big assumption this is being driven by a user sitting in front of a client.)
The idea makes sense to me, as it’s a way of establishing who is requesting info and be able to authorize the queries and mutations.
For graphql-ruby, this means setting up the Query graph like so:
The viewer type is reflective of the
User model in the data store,
which is what is contained in the
current_user in the context passed
in. That value can be obtained in a few ways: some typical to Rails
apps, through OAuth, through JWTs, etc. It’s not especially important
here how the current user is determined to the graphql system, as it
should be. Here we can see that if there is no current user in the
context, a “Null User” object is returned.
For sake of clarity, the
Giving the above a query like:
Will return a JSON object like:
Here’s something I’m doing, which I haven’t seen anywhere else yet.
The application is the canonical micropost system, with users, posts, and (eventually) comments.
Posts belong to Users, Comments belong to both Users and Posts. A rule
would be that all published posts are visible to everyone, and these
are gathered with the
Another rule would be that only the post’s author can update, publish, or delete a given post
So, a query from an anonymous user would have the published posts, but
my_posts would be an empty set.
Another way to sort this is have multiple root fields in the base query, but this seems frowned on.
My small learning project supporting this learning is at https://github.com/tamouse/r5_graphql_react. Feel free to contribute, comment, etc. I’m still a beginner at this and would appreciate feedback.