DD.WellWorkover.Cloud/AsbCloudInfrastructure/Services/PermissionService.cs
Фролов 551c60c4ff Add/refactor services for permissions authorization model.
Rename some fields in DB.permission.
2021-12-11 16:46:04 +05:00

83 lines
2.8 KiB
C#

using AsbCloudApp.Data;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services.Cache;
using Mapster;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Services
{
public class PermissionService : IPermissionService, IConverter<PermissionDto, Permission>
{
private readonly CacheTable<Permission> cachePermission;
public PermissionService(IAsbCloudDbContext db, CacheDb cacheDb)
{
cachePermission = cacheDb.GetCachedTable<Permission>(
(AsbCloudDbContext)db,
new string[] { nameof(Permission.PermissionInfo) });
}
public async Task<IEnumerable<PermissionDto>> GetByIdRoleAsync(int idRole, CancellationToken token)
{
var entities = await cachePermission
.WhereAsync(p => p.IdUserRole == idRole, token)
.ConfigureAwait(false);
var dto = entities.Select(Convert);
return dto;
}
public async Task<int> InsertRangeAsync(IEnumerable<PermissionDto> dtos, CancellationToken token)
{
var entities = dtos.Select(Convert);
return (await cachePermission.InsertAsync(entities, token))?.Count()??0;
}
public async Task<int> UpdateAsync(PermissionDto dto, CancellationToken token)
{
var entity = Convert(dto);
await cachePermission.UpsertAsync(entity, token)
.ConfigureAwait(false);
return 1;
}
public Task<int> DeleteAsync(int idUserRole, int idPermission, CancellationToken token)
{
bool predicate(Permission p) => p.IdUserRole == idUserRole && p.IdPermissionInfo == idPermission;
return DeleteAsync(predicate, token);
}
public Task<int> DeleteAllByRoleAsync(int idUserRole, CancellationToken token)
{
bool predicate(Permission p) => p.IdUserRole == idUserRole;
return DeleteAsync(predicate, token);
}
private async Task<int> DeleteAsync(Func<Permission, bool> predicate, CancellationToken token)
{
var count = (await cachePermission.WhereAsync(predicate, token).ConfigureAwait(false)).Count();
if (count > 0)
await cachePermission.RemoveAsync(predicate, token)
.ConfigureAwait(false);
return count;
}
public Permission Convert(PermissionDto src)
{
var entity = src.Adapt<Permission>();
return entity;
}
public PermissionDto Convert(Permission src)
{
var dto = src.Adapt<PermissionDto>();
dto.PermissionName = src.PermissionInfo?.Name;
return dto;
}
}
}