DD.WellWorkover.Cloud/AsbCloudInfrastructure/Services/PermissionService.cs
2021-12-17 12:38:34 +05:00

90 lines
3.3 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
{
private readonly CacheTable<RelationUserRolePermission> cacheUserRolePermission;
private readonly CacheTable<Permission> cachePermission;
public PermissionService(IAsbCloudDbContext db, CacheDb cacheDb)
{
cacheUserRolePermission = cacheDb.GetCachedTable<RelationUserRolePermission>(
(AsbCloudDbContext)db,
new string[] { nameof(RelationUserRolePermission.Permission) });
cachePermission = cacheDb.GetCachedTable<Permission>(
(AsbCloudDbContext)db);
}
public async Task<IEnumerable<PermissionDto>> GetByIdRoleAsync(int idRole, CancellationToken token)
{
var entities = await cacheUserRolePermission
.WhereAsync(p => p.IdUserRole == idRole, token)
.ConfigureAwait(false);
var dto = entities.Select(e => e.Permission).Adapt<PermissionDto>();
return dto;
}
public async Task<int> InsertRangeAsync(IEnumerable<PermissionDto> dtos, CancellationToken token)
{
foreach (var dto in dtos)
{
var entity = Convert(dto);
var insertedEntity = cachePermission.Insert(entity);
cacheUserRolePermission.Insert(new RelationUserRolePermission()
{
IdPermission = insertedEntity.Id,
IdUserRole = dto.IdUserRole
});
}
return 1;
}
public async Task<int> UpdateAsync(PermissionDto dto, CancellationToken token)
{
var entity = Convert(dto);
await cachePermission.UpsertAsync(entity, token)
.ConfigureAwait(false);
return 1;
}
public async Task<int> DeleteAsync(int idUserRole, int idPermission, CancellationToken token)
{
bool predicate(RelationUserRolePermission p) => p.IdUserRole == idUserRole && p.IdPermission == idPermission;
await DeleteAsync(predicate, token);
cachePermission.Remove(p => p.Id == idPermission);
return 1;
}
public Task<int> DeleteAllByRoleAsync(int idUserRole, CancellationToken token)
{
bool predicate(RelationUserRolePermission p) => p.IdUserRole == idUserRole;
return DeleteAsync(predicate, token);
}
private async Task<int> DeleteAsync(Func<RelationUserRolePermission, bool> predicate, CancellationToken token)
{
var count = (await cacheUserRolePermission.WhereAsync(predicate, token).ConfigureAwait(false)).Count();
if (count > 0)
await cacheUserRolePermission.RemoveAsync(predicate, token)
.ConfigureAwait(false);
return count;
}
public Permission Convert(PermissionDto src)
{
var entity = src.Adapt<Permission>();
return entity;
}
}
}