Files
FoodsharingOnboarding/FoodsharingSiegen.Server/Data/Service/AuditService.cs
Andre Beging e19268f3eb Refactoring
2025-03-28 17:18:49 +01:00

99 lines
3.0 KiB
C#

using FoodsharingSiegen.Contracts;
using FoodsharingSiegen.Contracts.Entity;
using FoodsharingSiegen.Server.Auth;
using Microsoft.EntityFrameworkCore;
namespace FoodsharingSiegen.Server.Data.Service
{
/// <summary>
/// The audit service class (a. beging, 23.05.2022)
/// </summary>
/// <seealso cref="ServiceBase"/>
public class AuditService : ServiceBase
{
#region Setup/Teardown
/// <summary>
/// Initializes a new instance of the <see cref="AuditService"/> class
/// </summary>
/// <param name="context">The context (ab)</param>
/// <param name="authService"></param>
public AuditService(FsContext context, AuthService authService) : base(context, authService) { }
#endregion
#region Public Method Insert
/// <summary>
/// Inserts the type (a. beging, 23.05.2022)
/// </summary>
/// <param name="type">The type</param>
/// <param name="data1">The data</param>
/// <param name="data2">The data</param>
/// <returns>A task containing an operation result of audit</returns>
public async Task<OperationResult<Audit>> Insert(AuditType type, string? data1 = null, string? data2 = null)
{
try
{
var audit = new Audit
{
Created = DateTime.Now,
Type = type,
UserID = CurrentUser?.Id,
Data1 = data1,
Data2 = data2
};
Context.Audits?.Add(audit);
var saveR = await Context.SaveChangesAsync();
if (saveR > 0)
return new(audit);
return new(new Exception("Couldn't add audit"));
}
catch (Exception e)
{
return new(e);
}
}
#endregion
#region Public Method Load
/// <summary>
/// Loads the count (a. beging, 23.05.2022)
/// </summary>
/// <param name="count">The count</param>
/// <param name="type">The type</param>
/// <returns>A task containing an operation result of list audit</returns>
public async Task<OperationResult<List<Audit>>> Load(int count, AuditType? type = null)
{
try
{
await Task.CompletedTask;
var query = Context.Audits?.Include(x => x.User).OrderByDescending(x => x.Created).AsQueryable();
if (count > 0)
query = query?.Take(count);
if (type != null)
query = query?.Where(x => x.Type == type);
var mat = query?.ToList();
if (mat != null) return new(mat);
return new(new Exception("Couldn't load audits"));
}
catch (Exception e)
{
return new(e);
}
}
#endregion
}
}