Skip to content

Instantly share code, notes, and snippets.

@jraps20
Last active January 29, 2023 13:33
Show Gist options
  • Save jraps20/10262931127d51fc2297bdd9fcb4a29c to your computer and use it in GitHub Desktop.
Save jraps20/10262931127d51fc2297bdd9fcb4a29c to your computer and use it in GitHub Desktop.
namespace MyClient.Foundation.Services
{
using Sitecore.Data.Items;
using Sitecore.ExperienceEdge.Connector.Abstraction.DirectPublishing;
public class EdgeService : IEdgeService
{
private const string EdgePublishingTargetId = "{3013BEED-71CA-4DE3-A1D2-17DD871597F1}";
/// <summary>
/// This is confirmed to also be a singleton, thus this class is as well
/// </summary>
private readonly IItemPublishingManager itemPublishManager;
public EdgeService(IItemPublishingManager itemPublishManager)
{
this.itemPublishManager = itemPublishManager;
}
/// <summary>
/// During a publish to Edge, the Edge Connector must generate the rendered markup of a page. It does so by setting a "DummyHttpContext".
/// We can leverage this fact to our advantage during rendering by requesting items that are only eligible for Edge publishing.
/// This is useful within a Rendering Contents Resolver if additional items are needed to populate the JSON object. Each object can be
/// checked for eligibility.
/// </summary>
public bool IsEdgePublishingContext()
{
var requestParams = Sitecore.Context.HttpContext?.Request?.Params;
// the dummy request of the Edge Connector has a variety of properties that can be keyed on, but we chose requestParams
if(requestParams == null)
{
return false;
}
return requestParams.Count == 0;
}
public Item GetEligibleRenderingItem(Item item)
{
if(item == null)
{
return null;
}
// if it is targeting a database other than web, just return the original item
if (item.Database?.Name != "master")
{
return item;
}
// here is where we know it's targeting the master database, now we need to check if the Edge connector is generating the layout
if (this.IsEdgePublishingContext())
{
// if so, we need to get the eligible version of the item, not just the latest version as it may have restrictions
return this.itemPublishManager.GetPublishableVersion(item, new Sitecore.Data.ID(EdgePublishingTargetId), false);
}
return item;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment