JSS: How to Use Graphql Query and Rendering Contents Resolver Together

Artsem Prashkovich on September 10, 2020

There are two options how rendering and its associated data are serialized: Rendering Contents Resolver and Component GraphQL Query (read about comparison of them by the following link: Comparison of GraphQL query vs Rendering Content Resolving

By default, only one of them can be used. Once the Component GraphQL Query field has any value, the Rendering Content Resolver is not utilized any more. But sometimes it is good to have both of them enabled at the same time. For example, when you need to use a Rendering Content Resolver to get and calculate data from a third party, and still want to get data from a datasource or context item which is easier to reach via GraphQL. In this article I will show how we can achieve that.

First of all, we need to revert the original RenderingContentsResolver, which was overridden by GraphQL provider. It definitely works fine, but it has wrong logic in terms of our goal. It provides data from GraphQL only in case of an  empty Rendering Contents Resolver field.

Revering default processor

The config file is available here

Then, we need to implement a GraphQLContentsResolver processor which will extend the output with a data from GraphQL query:

GraphQL Contents Resolver 

The complete code is available by the link.

Then we need to patch the configuration to register the processor:

 Register a new processor

The config file is available here

The code above will be run after the Sitecore.LayoutService.Presentation.Pipelines.RenderJsonRendering.ResolveRenderingContents that retrieves data using Rendering Content Resolver selected on the rendering item.

The currently created processor uses a default Sitecore’s GraphQLAwareRenderingContentsResolver to execute GraphQL query and extend the already existing content.

Now, rendering associated data is always extended with a GraphQL query execution results if the query is set.. Only one thing is left. I also want to be able to use GraphQL only. It is very simple, we need to implement a custom Rendering Content Resolver which returns empty object:

Empty Rendering Content Resolver

The complete code is available by the link.

Then create a Rendering Content Resolver item in Sitecore:

GraphQL Query Only item

There are three possible variants to serialize rendering data:

- Rendering Content Resolver and GraphQL - choose resolver and add GraphQL query
- Only Rendering Content Resolver - choose resolver and keep GraphQL query empty
- Only GraphQL query - choose GraphQL Query Only resolver and add GraphQL query