LANCommander/LANCommander.Server.Services/UserCustomFieldService.cs
Pat Hartl b28e8a51ee Fix auditing
The way updates are being handled means that the auditing interceptor doesn't work as the entities are not showing in the change tracker at that stage as modified. Added the auditing to BaseDatabaseService instead.
2025-02-09 18:53:40 -06:00

71 lines
2.2 KiB
C#

using AutoMapper;
using LANCommander.Server.Data;
using LANCommander.Server.Data.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using ZiggyCreatures.Caching.Fusion;
namespace LANCommander.Server.Services
{
public sealed class UserCustomFieldService(
ILogger<UserCustomFieldService> logger,
IFusionCache cache,
IMapper mapper,
IHttpContextAccessor httpContextAccessor,
IDbContextFactory<DatabaseContext> contextFactory) : BaseDatabaseService<UserCustomField>(logger, cache, mapper, httpContextAccessor, contextFactory)
{
public override async Task<UserCustomField> UpdateAsync(UserCustomField entity)
{
return await base.UpdateAsync(entity, async context =>
{
await context.UpdateRelationshipAsync(ucf => ucf.User);
});
}
public async Task<UserCustomField> GetAsync(Guid userId, string name)
{
return await FirstOrDefaultAsync(cf => cf.UserId == userId && cf.Name == name);
}
public async Task UpdateAsync(Guid userId, string name, string value)
{
if (name.Length > 64)
throw new ArgumentException("Field name must be 64 characters or shorter");
if (value.Length > 1024)
throw new ArgumentException("Field value must be 1024 characters or less");
var existing = await GetAsync(userId, name);
if (existing.Value == value)
return;
if (existing == null)
{
await AddAsync(new UserCustomField
{
Name = name,
Value = value
});
}
else if (!String.IsNullOrWhiteSpace(value))
{
existing.Value = value;
await UpdateAsync(existing);
}
else
{
await DeleteAsync(userId, name);
}
}
public async Task DeleteAsync(Guid userId, string name)
{
var existing = await GetAsync(userId, name);
await DeleteAsync(existing);
}
}
}