Filter items without language version in Sitecore Item Web API

The Sitecore Item Web API is a great tool to query Sitecore client side and retrieve JSON data which can be shown through a JavaScript library like Angular or Knockout. The Item Web API will return all items that match a query even if there is no version of an item in the current language. This can lead to unnecessarily large HTTP responses which will slow down the page, especially in multilingual sites with many languages with different content per language.

One nice feature of Item Web API is the ability to easily customize it. Below simple pipeline can be added to filter out any item that matches a query but does not have a version in the current language:

using Sitecore.Diagnostics;
using Sitecore.ItemWebApi.Pipelines.Read;
using Sitecore.Web;
using System.Linq;

namespace Jeroen.Pipelines.WebAPI
{
    public class RemoveItemsWithoutLanguageVersion : ReadProcessor
    {
        public override void Process(ReadArgs arguments)
        {
            Assert.ArgumentNotNull(arguments, "arguments");

            if (WebUtil.GetQueryString("language-filter", null) == "1")
            {
                arguments.Scope = arguments.Scope.Where(i => i.Versions.Count > 0).ToArray();
            }
        }
    }
}

I’m only doing this filtering when a query string of language-filter=1 is passed. I add this to every query that needs it. This avoids any conflicts with existing functionality which uses Item Web API like the Sitecore Desktop. Above pipeline is enabled in Sitecore.ItemWebApi.config as follows:

<itemWebApiRead>
   <processor type="Jeroen.Pipelines.WebAPI.RemoveItemsWithoutLanguageVersion, Jeroen.Pipelines" />
 </itemWebApiRead>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s