Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Context vs RootValue in Apollo GraphQL

In graphQLOptions, what is the difference between context and rootvalue?

When should I use one, and when should I use the other?

At the moment I'm attaching connectors and other sensitive data to the context, is this safe? Can the user read the context or the rootvalue of his queries?

like image 963
Mascarpone Avatar asked Jun 03 '17 13:06

Mascarpone


2 Answers

RootValue is an initial value passed in to the entry point of a query. Its undefined by default, but Apollo allows you to seed the query with some values if thats appropriate for your use case. It's accessible as the first parameter in the resolver function signature.

context is a shared reference available to all resolvers. Typically its an object of key/val pairs containing handles to stateful external connections or meta concerns like users/auth/etc.

Users (I'm assuming you mean clients) can only read what you return from resolvers; context is not represented in the introspection query. It's safe to put sensitive data and connectors (in the Apollo paradigm) there if your resolvers need access to fulfill their responsibilities.

like image 105
Justin Mandzik Avatar answered Oct 12 '22 06:10

Justin Mandzik


GraphQL types/fields concept is quite recursive. The usually called RootQuery is as much a custom type as any other type in your schema. Usually, though, this RootQuery type contains only dynamically resolved fields, but this is no limitation. If you want people to access a string scalar name field on a User type you don't need to write a resolver function for it, as long as the object resolved to any User returning field contains that name property; this works just the same way with the RootValue, but that object will be the object provided via rootValue.

Context, in the other hand, is something that will be made available to every resolver, but will never be queriable by any user sending queries against the GraphQL server - thus making context the perfect place for keeping sensitive data, such as session information.

Sample: here goes a sample usage of rootValue: https://runkit.com/lucasconstantino/graphql-root-value-sample

like image 8
Lucas Constantino Silva Avatar answered Oct 12 '22 06:10

Lucas Constantino Silva