Last active
September 1, 2020 11:19
-
-
Save vitaliitylyk/c011bf4e03237301959d8d29f7303f44 to your computer and use it in GitHub Desktop.
A custom Sitecore JSS rendering contents resolver, which appends results of a GraphQL query defined on a rendering item to LayoutService output. This allows to execute both Rendering Contents Resolver logic and integrated GraphQL query. More information at https://blog.vitaliitylyk.com/combining-integrated-graphql-and-rendering-contents-resolver…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.Extensions.DependencyInjection; | |
using Newtonsoft.Json.Linq; | |
using Sitecore.JavaScriptServices.GraphQL.LayoutService; | |
using Sitecore.LayoutService.Configuration; | |
using Sitecore.LayoutService.ItemRendering.ContentsResolvers; | |
using Sitecore.Mvc.Presentation; | |
using System; | |
namespace VitaliiTylyk.JavascriptServices.RenderingContentsResolvers | |
{ | |
/// <summary> | |
/// Appends results of a GraphQL query defined on a rendering item to LayoutService output. | |
/// This allows to execute both Rendering Contents Resolver logic and integrated GraphQL query. | |
/// </summary> | |
public class GraphQLCombinedResolver : RenderingContentsResolver | |
{ | |
private readonly IServiceProvider serviceProvider; | |
public GraphQLCombinedResolver(IServiceProvider serviceProvider) | |
{ | |
this.serviceProvider = serviceProvider; | |
} | |
public override object ResolveContents(Rendering rendering, IRenderingConfiguration renderingConfig) | |
{ | |
var contents = (JObject)base.ResolveContents(rendering, renderingConfig); | |
var query = rendering.RenderingItem.InnerItem[Sitecore.JavaScriptServices.Core.FieldIDs.JsonRendering.GraphQLQuery]; | |
if (string.IsNullOrWhiteSpace(query)) | |
{ | |
return contents; | |
} | |
var graphqlResolver = ActivatorUtilities.GetServiceOrCreateInstance(serviceProvider, typeof(GraphQLAwareRenderingContentsResolver)) as IRenderingContentsResolver; | |
contents["additionalData"] = (JObject)graphqlResolver.ResolveContents(rendering, renderingConfig); | |
return contents; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment