Skip to content

Instantly share code, notes, and snippets.

@smdooley
Created May 25, 2023 09:33
Show Gist options
  • Save smdooley/8db6f64cbf63516efc770cd59278b113 to your computer and use it in GitHub Desktop.
Save smdooley/8db6f64cbf63516efc770cd59278b113 to your computer and use it in GitHub Desktop.
Extending Umbraco Content Delivery API
using Umbraco.Cms.Core.DeliveryApi;
namespace UmbracoPlayground.UI.Application.Filters
{
public class AuthorFilter : IFilterHandler
{
private const string FilterType = "author:";
public FilterOption BuildFilterOption(string filter)
{
var value = filter.Substring(FilterType.Length);
return new FilterOption
{
FieldName = "author",
Operator = FilterOperation.Is,
Values = new[] { value }
};
}
public bool CanHandle(string query)
{
return string.IsNullOrWhiteSpace(query)
? false
: query.StartsWith(FilterType, StringComparison.OrdinalIgnoreCase);
}
}
}
using System;
using Umbraco.Cms.Core.DeliveryApi;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Web;
namespace UmbracoPlayground.UI.Application.Filters
{
public class AuthorIndexer : IContentIndexHandler
{
private readonly IUmbracoContextFactory _umbracoContextFactory;
public AuthorIndexer(IUmbracoContextFactory umbracoContextFactory)
{
_umbracoContextFactory = umbracoContextFactory;
}
public IEnumerable<IndexField> GetFields()
{
return new[]
{
new IndexField
{
FieldName = "author",
FieldType = FieldType.StringSortable,
VariesByCulture = false
}
};
}
public IEnumerable<IndexFieldValue> GetFieldValues(IContent content, string? culture)
{
var authorId = content.GetValue<GuidUdi>("author");
if (authorId == null)
{
return Enumerable.Empty<IndexFieldValue>();
}
var context = _umbracoContextFactory.EnsureUmbracoContext();
if (context == null) return Enumerable.Empty<IndexFieldValue>();
var node = context?.UmbracoContext?.Content?.GetById(authorId);
if(node == null) return Enumerable.Empty<IndexFieldValue>();
return new[]
{
new IndexFieldValue
{
FieldName = "author",
Values = new object[] { node.Name }
}
};
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment