Skip to content

Instantly share code, notes, and snippets.

@Hangsolow
Created April 25, 2020 15:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hangsolow/c8496b562eb300eb2af8fb28f3264a5c to your computer and use it in GitHub Desktop.
Save Hangsolow/c8496b562eb300eb2af8fb28f3264a5c to your computer and use it in GitHub Desktop.
An ContentApiSerializer that removes null/empty values and unused properties
public class CleaningContentSerializer : IContentApiSerializer
{
public CleaningContentSerializer(IContentApiSerializer defaultSerializer)
{
DefaultSerializer = defaultSerializer;
}
public string MediaType => DefaultSerializer.MediaType;
public Encoding Encoding => DefaultSerializer.Encoding;
private IContentApiSerializer DefaultSerializer { get; }
public string Serialize(object value)
{
CleanObject(value);
return DefaultSerializer.Serialize(value);
}
private void CleanObject(object value)
{
switch (value)
{
case ContentApiModel model:
CleanContentApiModel(model);
break;
case IEnumerable<ContentApiModel> models:
CleanContentApiModels(models);
break;
}
void CleanContentApiModel(ContentApiModel model)
{
//we have no need for these
model.Changed = null;
model.Created = null;
model.ExistingLanguages = null;
model.MasterLanguage = null;
model.Saved = null;
model.StartPublish = null;
model.StopPublish = null;
model.Status = null;
model.ParentLink = null;
var properties = model.Properties;
//only used serverside
RemoveProperty(properties, "PreScripts");
RemoveProperty(properties, "PostScripts");
RemoveProperty(properties, "BodyScripts");
RemoveProperty(properties, "SiteSettings");
RemoveProperty(properties, "PersonalizedSiteSettings");
var removeList = new List<string>();
foreach (var property in properties)
{
CheckProperty(property, removeList);
}
foreach (var removeKey in removeList)
{
properties.Remove(removeKey);
}
}
void CheckProperty(KeyValuePair<string, object> property, IList<string> removalList)
{
switch (property.Value)
{
case null:
removalList.Add(property.Key);
break;
case string str when string.IsNullOrEmpty(str):
removalList.Add(property.Key);
break;
case ICollection collection when collection.Count == 0:
removalList.Add(property.Key);
break;
case IEnumerable<ContentApiModel> models when models.Any():
CleanContentApiModels(models);
break;
case IEnumerable<ContentApiModel> models:
removalList.Add(property.Key);
break;
}
}
void CleanContentApiModels(IEnumerable<ContentApiModel> models)
{
foreach (var model in models)
{
CleanContentApiModel(model);
}
}
void RemoveProperty(IDictionary<string,object> properties, string key)
{
if (properties.ContainsKey(key))
{
properties.Remove(key);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment