LANCommander/LANCommander.Server.ImportExport/Importers/CollectionImporter.cs

75 lines
2.4 KiB
C#
Raw Permalink Normal View History

2025-04-11 02:31:29 -05:00
using AutoMapper;
using LANCommander.SDK.Enums;
using LANCommander.SDK.Models.Manifest;
using LANCommander.Server.ImportExport.Exceptions;
using LANCommander.Server.ImportExport.Models;
using LANCommander.Server.Services;
2025-03-29 17:58:00 -05:00
namespace LANCommander.Server.ImportExport.Importers;
2025-03-29 17:58:00 -05:00
public class CollectionImporter(
2025-04-11 02:31:29 -05:00
IMapper mapper,
2025-07-26 19:19:38 -05:00
CollectionService collectionService,
GameService gameService) : BaseImporter<Collection, Data.Models.Collection>
2025-03-29 17:58:00 -05:00
{
public override async Task<ImportItemInfo> GetImportInfoAsync(Collection record)
{
return new ImportItemInfo
{
Type = ImportExportRecordType.Collection,
Name = record.Name,
};
}
public override bool CanImport(Collection record) => ImportContext.DataRecord is Data.Models.Game;
2025-04-11 02:31:29 -05:00
public override async Task<Data.Models.Collection> AddAsync(Collection record)
2025-03-29 17:58:00 -05:00
{
try
{
var collection = new Data.Models.Collection
{
Games = new List<Data.Models.Game>() { ImportContext.DataRecord as Data.Models.Game },
2025-03-29 17:58:00 -05:00
Name = record.Name,
};
collection = await collectionService.AddAsync(collection);
2025-03-29 17:58:00 -05:00
2025-03-29 20:10:35 -05:00
return collection;
2025-03-29 17:58:00 -05:00
}
catch (Exception ex)
{
throw new ImportSkippedException<Collection>(record, "An unknown error occured while importing collection", ex);
}
}
public override async Task<Data.Models.Collection> UpdateAsync(Collection record)
2025-03-29 17:58:00 -05:00
{
var existing = await collectionService.Include(c => c.Games).FirstOrDefaultAsync(c => c.Name == record.Name);
2025-07-26 19:19:38 -05:00
var game = ImportContext.DataRecord as Data.Models.Game;
2025-03-29 17:58:00 -05:00
try
{
if (existing.Games == null)
existing.Games = new List<Data.Models.Game>();
2025-07-26 19:19:38 -05:00
if (!existing.Games.Any(g => g.Id == game.Id))
{
existing.Games.Add(await gameService.GetAsync(game.Id));
existing = await collectionService.UpdateAsync(existing);
}
2025-03-29 17:58:00 -05:00
2025-03-29 20:10:35 -05:00
return existing;
2025-03-29 17:58:00 -05:00
}
catch (Exception ex)
{
throw new ImportSkippedException<Collection>(record, "An unknown error occured while importing collection", ex);
}
}
public override async Task<bool> ExistsAsync(Collection record)
2025-03-29 17:58:00 -05:00
{
return await collectionService.ExistsAsync(c => c.Name == record.Name);
2025-03-29 17:58:00 -05:00
}
}