[CHANGE] Moved repositories to new monads

This commit is contained in:
max 2025-04-12 14:20:40 +02:00
parent ec7e260511
commit 7ed219d08a
6 changed files with 135 additions and 189 deletions

View File

@ -1,114 +1,86 @@
using DotBased.AspNet.Authority.Models;
using DotBased.AspNet.Authority.Models.Authority; using DotBased.AspNet.Authority.Models.Authority;
using DotBased.AspNet.Authority.Repositories; using DotBased.AspNet.Authority.Repositories;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace DotBased.AspNet.Authority.EFCore.Repositories; namespace DotBased.AspNet.Authority.EFCore.Repositories;
public class AttributeRepository(IDbContextFactory<AuthorityContext> contextFactory) : RepositoryBase, IAttributeRepository public class AttributeRepository(IDbContextFactory<AuthorityContext> contextFactory, ILogger<AttributeRepository> logger) : RepositoryBase, IAttributeRepository
{ {
public async Task<ListResultOld<AuthorityAttributeItem>> GetAttributesAsync(int limit = 20, int offset = 0, string search = "", public async Task<QueryItems<AuthorityAttributeItem>> GetAttributesAsync(int limit = 20, int offset = 0, string search = "",
CancellationToken cancellationToken = default) CancellationToken cancellationToken = default)
{ {
try await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var query = context.Attributes.AsQueryable();
if (!string.IsNullOrEmpty(search))
{ {
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken); query = query.Where(a => $"{a.AttributeKey} {a.ForeignKey} {a.AttributeValue}".Contains(search, StringComparison.CurrentCultureIgnoreCase));
var query = context.Attributes.AsQueryable(); }
if (!string.IsNullOrEmpty(search))
{
query = query.Where(a => $"{a.AttributeKey} {a.ForeignKey} {a.AttributeValue}".Contains(search, StringComparison.CurrentCultureIgnoreCase));
}
var total = await query.CountAsync(cancellationToken); var total = await query.CountAsync(cancellationToken);
var select = await query.OrderBy(a => a.AttributeKey).Skip(offset).Take(limit).Select(a => new AuthorityAttributeItem() var select = await query.OrderBy(a => a.AttributeKey).Skip(offset).Take(limit).Select(a => new AuthorityAttributeItem()
{
BoundId = a.ForeignKey,
AttributeKey = a.AttributeKey,
AttributeValue = a.AttributeValue
}).ToListAsync(cancellationToken);
return ListResultOld<AuthorityAttributeItem>.Ok(select, total, limit, offset);
}
catch (Exception e)
{ {
return HandleExceptionListResult<AuthorityAttributeItem>("Failed to get attributes", e); BoundId = a.ForeignKey,
} AttributeKey = a.AttributeKey,
AttributeValue = a.AttributeValue
}).ToListAsync(cancellationToken);
return QueryItems<AuthorityAttributeItem>.Create(select, total, limit, offset);
} }
public async Task<ResultOld<AuthorityAttribute>> GetAttributeByKeyAsync(string key, CancellationToken cancellationToken = default) public async Task<AuthorityAttribute?> GetAttributeByKeyAsync(string key, CancellationToken cancellationToken = default)
{ {
try await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
{ return await context.Attributes.FirstOrDefaultAsync(a => a.AttributeKey == key, cancellationToken);
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var attribute = await context.Attributes.FirstOrDefaultAsync(a => a.AttributeKey == key, cancellationToken);
return attribute == null ? ResultOld<AuthorityAttribute>.Failed("Attribute not found") : ResultOld<AuthorityAttribute>.Ok(attribute);
}
catch (Exception e)
{
return HandleExceptionResult<AuthorityAttribute>("Failed to get attribute by id", e);
}
} }
public async Task<ResultOld<AuthorityAttribute>> CreateAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default) public async Task<AuthorityAttribute?> CreateAttributeAsync(AuthorityAttribute attribute,
CancellationToken cancellationToken = default)
{ {
try await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (string.IsNullOrWhiteSpace(attribute.AttributeKey) || attribute.ForeignKey == Guid.Empty)
{ {
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken); throw new Exception($"Attribute {attribute.AttributeKey} not found");
if (string.IsNullOrWhiteSpace(attribute.AttributeKey) || attribute.ForeignKey == Guid.Empty)
{
return ResultOld<AuthorityAttribute>.Failed("Attribute key and/or bound id is empty");
}
var entry = context.Attributes.Add(attribute);
var saveResult = await context.SaveChangesAsync(cancellationToken);
return saveResult <= 0 ? ResultOld<AuthorityAttribute>.Failed("Failed to create attribute") : ResultOld<AuthorityAttribute>.Ok(entry.Entity);
}
catch (Exception e)
{
return HandleExceptionResult<AuthorityAttribute>("Failed to create attribute", e);
} }
var entry = context.Attributes.Add(attribute);
var saveResult = await context.SaveChangesAsync(cancellationToken);
return saveResult != 0 ? entry.Entity : null;
} }
public async Task<ResultOld<AuthorityAttribute>> UpdateAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default) public async Task<AuthorityAttribute?> UpdateAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default)
{ {
try await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var currentAttribute = await context.Attributes.FirstOrDefaultAsync(a => a.AttributeKey == attribute.AttributeKey, cancellationToken);
if (currentAttribute == null)
{ {
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken); return null;
var currentAttribute = await context.Attributes.FirstOrDefaultAsync(a => a.AttributeKey == attribute.AttributeKey, cancellationToken); }
if (currentAttribute == null)
{
return ResultOld<AuthorityAttribute>.Failed("Attribute not found");
}
if (currentAttribute.Version != attribute.Version) if (currentAttribute.Version != attribute.Version)
{ {
return ResultOld<AuthorityAttribute>.Failed("Attribute version doesn't match"); logger.LogError("Attribute version validation failed for attribute {attribute}", currentAttribute.AttributeKey);
} return null;
}
var entry = context.Attributes.Update(currentAttribute); var entry = context.Attributes.Update(currentAttribute);
var saveResult = await context.SaveChangesAsync(cancellationToken); var saveResult = await context.SaveChangesAsync(cancellationToken);
return saveResult <= 0 ? ResultOld<AuthorityAttribute>.Failed("Failed to update attribute") : ResultOld<AuthorityAttribute>.Ok(entry.Entity); return saveResult != 0 ? entry.Entity : null;
}
catch (Exception e)
{
return HandleExceptionResult<AuthorityAttribute>("Failed to update attribute", e);
}
} }
public async Task<ResultOld> DeleteAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default) public async Task<bool> DeleteAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default)
{ {
try await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var currentAttribute = await context.Attributes.FirstOrDefaultAsync(a => a.AttributeKey == attribute.AttributeKey, cancellationToken);
if (currentAttribute == null)
{ {
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken); logger.LogError("Attribute not found.");
var currentAttribute = await context.Attributes.FirstOrDefaultAsync(a => a.AttributeKey == attribute.AttributeKey, cancellationToken); return false;
if (currentAttribute == null)
{
return ResultOld.Failed("Attribute not found");
}
context.Attributes.Remove(currentAttribute);
var saveResult = await context.SaveChangesAsync(cancellationToken);
return saveResult <= 0 ? ResultOld.Failed("Failed to delete attribute") : ResultOld.Ok();
}
catch (Exception e)
{
return HandleException("Failed to delete attribute", e);
} }
context.Attributes.Remove(currentAttribute);
var saveResult = await context.SaveChangesAsync(cancellationToken);
return saveResult != 0;
} }
} }

View File

@ -1,130 +1,94 @@
using DotBased.AspNet.Authority.Models;
using DotBased.AspNet.Authority.Models.Authority; using DotBased.AspNet.Authority.Models.Authority;
using DotBased.AspNet.Authority.Repositories; using DotBased.AspNet.Authority.Repositories;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace DotBased.AspNet.Authority.EFCore.Repositories; namespace DotBased.AspNet.Authority.EFCore.Repositories;
public class GroupRepository(IDbContextFactory<AuthorityContext> contextFactory) : RepositoryBase, IGroupRepository public class GroupRepository(IDbContextFactory<AuthorityContext> contextFactory, ILogger<GroupRepository> logger) : RepositoryBase, IGroupRepository
{ {
public async Task<ListResultOld<AuthorityGroupItem>> GetGroupsAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default) public async Task<QueryItems<AuthorityGroupItem>> GetGroupsAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default)
{ {
try await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var query = context.Groups.AsQueryable();
if (!string.IsNullOrWhiteSpace(search))
{ {
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken); query = query.Where(g => $"{g.Name} {g.Id}".Contains(search));
var query = context.Groups.AsQueryable();
if (!string.IsNullOrWhiteSpace(search))
{
query = query.Where(g => $"{g.Name} {g.Id}".Contains(search));
}
var total = await query.CountAsync(cancellationToken);
var select = await query.OrderBy(g => g.Name).Skip(offset).Take(limit).Select(g => new AuthorityGroupItem()
{
Id = g.Id,
Name = g.Name
}).ToListAsync(cancellationToken);
return ListResultOld<AuthorityGroupItem>.Ok(select, total, limit, offset);
} }
catch (Exception e) var total = await query.CountAsync(cancellationToken);
var select = await query.OrderBy(g => g.Name).Skip(offset).Take(limit).Select(g => new AuthorityGroupItem()
{ {
return HandleExceptionListResult<AuthorityGroupItem>("Failed to get Groups", e); Id = g.Id,
} Name = g.Name
}).ToListAsync(cancellationToken);
return QueryItems<AuthorityGroupItem>.Create(select, total, limit, offset);
} }
public async Task<ResultOld<AuthorityGroup>> GetGroupByIdAsync(string id, CancellationToken cancellationToken = default) public async Task<AuthorityGroup?> GetGroupByIdAsync(string id, CancellationToken cancellationToken = default)
{ {
try await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (!Guid.TryParse(id, out var groupId))
{ {
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken); throw new Exception($"Invalid group id: {id}");
if (!Guid.TryParse(id, out var groupId))
{
return ResultOld<AuthorityGroup>.Failed("Invalid group id");
}
var group = await context.Groups.Where(g => g.Id == groupId).Include(g => g.Attributes).FirstOrDefaultAsync(cancellationToken: cancellationToken);
return ResultOld<AuthorityGroup>.HandleResult(group, "Group not found");
}
catch (Exception e)
{
return HandleExceptionResult<AuthorityGroup>("Failed to get Group", e);
} }
return await context.Groups.Where(g => g.Id == groupId).Include(g => g.Attributes).FirstOrDefaultAsync(cancellationToken: cancellationToken);
} }
public async Task<ListResultOld<AuthorityGroup>> GetUserGroupsAsync(AuthorityUser user, CancellationToken cancellationToken = default) public async Task<List<AuthorityGroup>> GetUserGroupsAsync(AuthorityUser user, CancellationToken cancellationToken = default)
{ {
try await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
{ var userJoinGroups = context.UserGroups.Where(ug => ug.UserId == user.Id).Select(ug => ug.GroupId);
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken); var userGroups = context.Groups.Where(g => userJoinGroups.Contains(g.Id));
var userJoinGroups = context.UserGroups.Where(ug => ug.UserId == user.Id).Select(ug => ug.GroupId); return userGroups.ToList();
var userGroups = context.Groups.Where(g => userJoinGroups.Contains(g.Id));
return ListResultOld<AuthorityGroup>.Ok(userGroups, userGroups.Count());
}
catch (Exception e)
{
return HandleExceptionListResult<AuthorityGroup>("Failed to get Groups", e);
}
} }
public async Task<ResultOld<AuthorityGroup>> CreateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default) public async Task<AuthorityGroup?> CreateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default)
{ {
try await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (group.Id == Guid.Empty)
{ {
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken); throw new Exception($"Invalid group id: {group.Id}");
if (group.Id == Guid.Empty)
{
return ResultOld<AuthorityGroup>.Failed("Id cannot be empty.");
}
var entry = context.Groups.Add(group);
var saveResult = await context.SaveChangesAsync(cancellationToken);
return saveResult <= 0 ? ResultOld<AuthorityGroup>.Failed("Failed to create group.") : ResultOld<AuthorityGroup>.Ok(entry.Entity);
}
catch (Exception e)
{
return HandleExceptionResult<AuthorityGroup>("Failed to create group!", e);
} }
var entry = context.Groups.Add(group);
var saveResult = await context.SaveChangesAsync(cancellationToken);
return saveResult != 0 ? entry.Entity : null;
} }
public async Task<ResultOld<AuthorityGroup>> UpdateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default) public async Task<AuthorityGroup?> UpdateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default)
{ {
try await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var currentGroup = await context.Groups.FirstOrDefaultAsync(g => g.Id == group.Id ,cancellationToken);
if (currentGroup == null)
{ {
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken); logger.LogError("Group with id {groupId} not found.", group.Id);
var currentGroup = await context.Groups.FirstOrDefaultAsync(g => g.Id == group.Id ,cancellationToken); return null;
if (currentGroup == null) }
{
return ResultOld<AuthorityGroup>.Failed("Group not found.");
}
if (currentGroup.Version != group.Version) if (currentGroup.Version != group.Version)
{ {
return ResultOld<AuthorityGroup>.Failed("Group version does not match, version validation failed!"); logger.LogError("Group version validation failed.");
} return null;
}
var entry = context.Groups.Update(group); var entry = context.Groups.Update(group);
var saveResult = await context.SaveChangesAsync(cancellationToken); var saveResult = await context.SaveChangesAsync(cancellationToken);
return saveResult <= 0 ? ResultOld<AuthorityGroup>.Failed("Failed to update group.") : ResultOld<AuthorityGroup>.Ok(entry.Entity); return saveResult != 0 ? entry.Entity : null;
}
catch (Exception e)
{
return HandleExceptionResult<AuthorityGroup>("Failed to update group!", e);
}
} }
public async Task<ResultOld> DeleteGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default) public async Task<bool> DeleteGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default)
{ {
try await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var currentGroup = await context.Groups.FirstOrDefaultAsync(g => g.Id == group.Id, cancellationToken);
if (currentGroup == null)
{ {
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken); logger.LogError("Group with id {groupId} not found.", group.Id);
var currentGroup = await context.Groups.FirstOrDefaultAsync(g => g.Id == group.Id, cancellationToken); return false;
if (currentGroup == null)
{
return ResultOld.Failed("Group not found, cannot delete group!");
}
context.Groups.Remove(currentGroup);
var saveResult = await context.SaveChangesAsync(cancellationToken);
return saveResult <= 0 ? ResultOld.Failed("Failed to delete group.") : ResultOld.Ok();
}
catch (Exception e)
{
return HandleException("Failed to delete group!", e);
} }
context.Groups.Remove(currentGroup);
var saveResult = await context.SaveChangesAsync(cancellationToken);
return saveResult != 0;
} }
} }

View File

@ -1,11 +1,19 @@
using DotBased.AspNet.Authority.Models.Authority; using DotBased.AspNet.Authority.Models.Authority;
using DotBased.Monads;
namespace DotBased.AspNet.Authority.Managers; namespace DotBased.AspNet.Authority.Managers;
public partial class AuthorityManager public partial class AuthorityManager
{ {
public async Task<ListResultOld<AuthorityGroup>> GetUserGroupsAsync(AuthorityUser user, CancellationToken cancellationToken = default) public async Task<Result<List<AuthorityGroup>>> GetUserGroupsAsync(AuthorityUser user, CancellationToken cancellationToken = default)
{ {
return await GroupRepository.GetUserGroupsAsync(user, cancellationToken); try
{
return await GroupRepository.GetUserGroupsAsync(user, cancellationToken);
}
catch (Exception e)
{
return e;
}
} }
} }

View File

@ -109,9 +109,9 @@ public partial class AuthorityManager
var searchIds = new List<Guid> { user.Id }; var searchIds = new List<Guid> { user.Id };
var usrGroups = await GetUserGroupsAsync(user, cancellationToken); var usrGroups = await GetUserGroupsAsync(user, cancellationToken);
if (usrGroups.Success) if (usrGroups.IsSuccess)
{ {
searchIds.AddRange(usrGroups.Items.Select(g => g.Id).ToList()); searchIds.AddRange(usrGroups.Value.Select(g => g.Id).ToList());
} }
var linkedRolesResult = await RoleRepository.GetLinkedRolesAsync(searchIds, cancellationToken); var linkedRolesResult = await RoleRepository.GetLinkedRolesAsync(searchIds, cancellationToken);

View File

@ -1,12 +1,13 @@
using DotBased.AspNet.Authority.Models;
using DotBased.AspNet.Authority.Models.Authority; using DotBased.AspNet.Authority.Models.Authority;
namespace DotBased.AspNet.Authority.Repositories; namespace DotBased.AspNet.Authority.Repositories;
public interface IAttributeRepository public interface IAttributeRepository
{ {
public Task<ListResultOld<AuthorityAttributeItem>> GetAttributesAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default); public Task<QueryItems<AuthorityAttributeItem>> GetAttributesAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default);
public Task<ResultOld<AuthorityAttribute>> GetAttributeByKeyAsync(string id, CancellationToken cancellationToken = default); public Task<AuthorityAttribute?> GetAttributeByKeyAsync(string id, CancellationToken cancellationToken = default);
public Task<ResultOld<AuthorityAttribute>> CreateAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default); public Task<AuthorityAttribute?> CreateAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default);
public Task<ResultOld<AuthorityAttribute>> UpdateAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default); public Task<AuthorityAttribute?> UpdateAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default);
public Task<ResultOld> DeleteAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default); public Task<bool> DeleteAttributeAsync(AuthorityAttribute attribute, CancellationToken cancellationToken = default);
} }

View File

@ -1,13 +1,14 @@
using DotBased.AspNet.Authority.Models;
using DotBased.AspNet.Authority.Models.Authority; using DotBased.AspNet.Authority.Models.Authority;
namespace DotBased.AspNet.Authority.Repositories; namespace DotBased.AspNet.Authority.Repositories;
public interface IGroupRepository public interface IGroupRepository
{ {
public Task<ListResultOld<AuthorityGroupItem>> GetGroupsAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default); public Task<QueryItems<AuthorityGroupItem>> GetGroupsAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default);
public Task<ResultOld<AuthorityGroup>> GetGroupByIdAsync(string id, CancellationToken cancellationToken = default); public Task<AuthorityGroup?> GetGroupByIdAsync(string id, CancellationToken cancellationToken = default);
public Task<ListResultOld<AuthorityGroup>> GetUserGroupsAsync(AuthorityUser user, CancellationToken cancellationToken = default); public Task<List<AuthorityGroup>> GetUserGroupsAsync(AuthorityUser user, CancellationToken cancellationToken = default);
public Task<ResultOld<AuthorityGroup>> CreateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default); public Task<AuthorityGroup?> CreateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default);
public Task<ResultOld<AuthorityGroup>> UpdateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default); public Task<AuthorityGroup?> UpdateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default);
public Task<ResultOld> DeleteGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default); public Task<bool> DeleteGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default);
} }