Skip to content

Commit

Permalink
feature: data type service extensions
Browse files Browse the repository at this point in the history
  • Loading branch information
jcdcdev committed Nov 8, 2023
1 parent a4b071c commit 523b6e1
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions src/jcdcdev.Umbraco.Core/Extensions/DataTypeServiceExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Services;
using Umbraco.Extensions;

namespace jcdcdev.Umbraco.Core.Extensions;

public static class DataTypeServiceExtensions
{
public static IEnumerable<EntityContainer> GetAllContainers(this IDataTypeService dataTypeService) => dataTypeService.GetContainers(Array.Empty<int>());

public static void DeleteAllEmptyContainers(this IDataTypeService dataTypeService)
{
var dataTypes = dataTypeService.GetAll();
var lookup = dataTypes.GroupBy(x => x.ParentId).ToLookup(x => x.Key, x => x.Count());
var containers = dataTypeService.GetAllContainers();

foreach (var container in containers)
{
var hasChildren = lookup.Contains(container.Id);

if (hasChildren)
{
continue;
}

dataTypeService.DeleteContainer(container.Id);
}
}

public static EntityContainer GetOrCreateFolder(
this IDataTypeService dataTypeService,
string folder,
int parentId = -1)
{
var dts = dataTypeService
.GetAllContainers()
.FirstOrDefault(x => x.ParentId == parentId && x.Name.InvariantEquals(folder));

if (dts == null)
{
dts = dataTypeService.CreateContainer(parentId, new Guid(), folder).Result?.Entity;
}

return dts ?? throw new Exception();
}
}

0 comments on commit 523b6e1

Please sign in to comment.