Remove Unwanted properties for Headless Implementation using Content Delivery API
While working with Headless, whenever we want to send data to the front end, many properties are also shown in JSON that we don't wish to, which creates a big and unreadable response.
To refactor that we can create Filter which will kick before and after every call.
Example:-
PreSerialization Content filter
- This class prevents the serialization of certain properties before the serialization
- Register that Service as Singleton
internal class PreSerializationContentFilter : ContentFilter<IContent>
{
public override void Filter(IContent content, ConverterContext converterContext)
{
content.Property.Remove("TopContentArea");
content.Property.Remove("MainContentArea");
content.Property.Remove("BottomContentArea");
content.Property.Remove("MetaTitle");
content.Property.Remove("MetaKeywords");
content.Property.Remove("MetaDescription");
content.Property.Remove("DisableIndexing");
content.Property.Remove("EnableNoFollow");
content.Property.Remove("OgContentType");
content.Property.Remove("Categories");
}
}
PostSerialization ApiModelFilter
- This generic class adds properties to the ContentApiModel after the serialization before sending the request
- Register that Service as Singleton
public class PostSerializationApiModelFilter : ContentApiModelFilter<ContentApiModel>
{
public override void Filter(ContentApiModel contentApiModel, ConverterContext converterContext)
{
try
{
// Set those values below as null, and configure ContentApiOption.IncludeNullValues = false in Initialization
// then, response data will not include those ones.
contentApiModel.ContentLink = null;
contentApiModel.Language = null;
contentApiModel.ExistingLanguages = null;
contentApiModel.MasterLanguage = null;
contentApiModel.ParentLink = null;
contentApiModel.StartPublish = null;
contentApiModel.StopPublish = null;
contentApiModel.RouteSegment = null;
contentApiModel.Changed = null;
contentApiModel.Created = null;
contentApiModel.Saved = null;
contentApiModel.Status = null;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
Using these classes you can remove unwanted properties.
Hope that helps !! :-)
Nice post, Thanks for sharing.