Context
In order to pass a service, or other values to be shared with all resolvers, the LiveResolverStore
provides a means of passing context. This gets passed to the third argument of all resolvers (live and non-live). This context argument analogous to the context argument used on the server which usually holds things like the database connection.
Setup​
In order to pass context to live resolvers, pass a resolverContext
argument to the initialization of LiveResolverStore
before creating the environment:
const store = new LiveResolverStore(source, {
resolverContext: {
store: customStore,
},
});
Usage in Resolvers​
- JavaScript
- Flow
The last argument in a resolver will contain the context type which contains the value passed into the store on initialization. If the resolver is on a model type or reads a @rootFragment
, the context value will be the third argument. If the resolver is not on a model type and does not read a @rootFragment
the context value will be passed as the thrid argument. Relay's generated artifacts will include generated type assertions to check that your resolver is typed correctly.
import type { LiveState } from 'relay-runtime';
/**
* @RelayResolver Query.counter: Int
* @live
*/
export function counter(
_args,
context
) {
return {
read: () => context.store.getState().counter,
subscribe: (callback) => {
return context.store.subscribe(callback);
},
};
}
Context is not currently supported in Flow
Type Checking​
In order to ensure that the resolver is implemented with the correct types, pass a resolverContextType
in the project config. This parameter expects a type name and a path
to import from:
{
"name": "project",
"language": "flow",
"resolverContextType": {
"name": "IResolverContextType",
"path": "path/to/file/IResolverContextType"
}
}
To import from a package, use the following syntax for a package
import:
{
"name": "project",
"language": "flow",
"resolverContextType": {
"name": "IResolverContextType",
"package": "@package/name"
}
}