JSS: Custom Content Resolver

Working with Sitecore JSS is a bit different than the traditional MVC approach. If you want to work the data your view uses before it gets to your view, in MVC you'd use a controller. In JSS, you use a content resolver.

JSS provides powerful ways of delievering your content without coding. For a simple rendering, you'd simply define a template, and then assign instances of that template as datasource for your rendering. With no coding required, you'd get well formatted and experience-editor ready JSON data.

But, even though this perverbial glove is very flexible, it's not one-size-its-all. Nothing ever is, really. Sometimes you are going to want to process and restructure the json data your server delievers to your clients.  

Content resolvers

The Layout service uses content resolvers for this purpose. You'll find them unser System -> Modules -> Layout Service -> Rendering Contents Resolvers.

If you let JSS create your content resolvers they'll use the Datasource Resolver by default, but there is a host of other resolvers that come OOB. There is a field on your json-renderings that defines which one you use, and if you create your own resolvers, they'll be selectable here.

 

If you want to create your own resolvers, you simply insert a new one into the Rendering Contents Resolvers folder in the tree, and then you define which class it points to as in the below image. You can also specify a sitecore query that resolves the items that are directed to your resolver, and parameters that you might want to access in your code.

For this example, I'm creating a simple resolver that if it has no datasource defined will check for a page level datasource field. Kind of handy if you have pages defined where multiple renderings often use the same datasource. As stated, this is a very simple resolver that only changes how the resolver determines the context item. You can make much more sophisticated resolvers than this. And note that the "entry method" that the layout service will call on your resolver is called ResolveContents (similar to the Process method of custom pipeline processors). For this example I don't want to change anything in this method, but i Included it in the sample code below for clarity. Also note that the return type for the ResolveContents method is object. You can return any old object (including dynamic objects) from this metod, and it will be run through a JSON serializer and get spit out as JSON through the Layout Service.

And the code would look something like this (preferably with a bit more error handling and less magic field strings perhaps):

PageLevelDatasourceResolver

 

08 Jul 2019, by Bonny Nilsson | 

layout Service, JSS, Content Resolvers