From 576d119674f015cd3526ee6e970afbdf01779559 Mon Sep 17 00:00:00 2001 From: KharchenkoVladimir Date: Thu, 25 Nov 2021 11:55:52 +0500 Subject: [PATCH] CS2-123: Changed UserRoleService and controller to inherit CrudController/service --- AsbCloudInfrastructure/DependencyInjection.cs | 2 +- .../Services/CrudServiceBase.cs | 5 +- .../Services/UserRoleService.cs | 74 ++++++-------- .../Controllers/AdminUserRoleController.cs | 96 +------------------ 4 files changed, 38 insertions(+), 139 deletions(-) diff --git a/AsbCloudInfrastructure/DependencyInjection.cs b/AsbCloudInfrastructure/DependencyInjection.cs index 080c9ac4..580bb356 100644 --- a/AsbCloudInfrastructure/DependencyInjection.cs +++ b/AsbCloudInfrastructure/DependencyInjection.cs @@ -48,7 +48,6 @@ namespace AsbCloudInfrastructure services.AddTransient(); services.AddTransient(); services.AddTransient(); - services.AddTransient(); // admin crud services: services.AddTransient, CrudServiceBase>(); @@ -56,6 +55,7 @@ namespace AsbCloudInfrastructure services.AddTransient, CrudServiceBase>(); services.AddTransient, CrudServiceBase>(); services.AddTransient, CrudServiceBase>(); + services.AddTransient, CrudServiceBase>(); services.AddTransient, CrudServiceBase>(); services.AddTransient, DrillParamsService>(); diff --git a/AsbCloudInfrastructure/Services/CrudServiceBase.cs b/AsbCloudInfrastructure/Services/CrudServiceBase.cs index e1b1cdb0..e0a49083 100644 --- a/AsbCloudInfrastructure/Services/CrudServiceBase.cs +++ b/AsbCloudInfrastructure/Services/CrudServiceBase.cs @@ -81,12 +81,13 @@ namespace AsbCloudInfrastructure.Services return dto; } - public virtual Task InsertAsync(TDto item, CancellationToken token = default) + public virtual async Task InsertAsync(TDto item, CancellationToken token = default) { var entity = Convert(item); entity.Id = 0; dbSet.Add(entity); - return context.SaveChangesAsync(token); + await context.SaveChangesAsync(token); + return entity.Id; } public virtual Task InsertRangeAsync(IEnumerable items, CancellationToken token = default) diff --git a/AsbCloudInfrastructure/Services/UserRoleService.cs b/AsbCloudInfrastructure/Services/UserRoleService.cs index 286d333f..dbc7050e 100644 --- a/AsbCloudInfrastructure/Services/UserRoleService.cs +++ b/AsbCloudInfrastructure/Services/UserRoleService.cs @@ -3,95 +3,79 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; using AsbCloudApp.Data; -using AsbCloudApp.Services; using AsbCloudDb.Model; using AsbCloudInfrastructure.Services.Cache; using Mapster; namespace AsbCloudInfrastructure.Services { - public class UserRoleService : IUserRoleService + public class UserRoleService : CrudServiceBase { - private readonly IAsbCloudDbContext db; private readonly CacheTable cacheUserRoles; private readonly CacheTable cachePermissions; private readonly CacheTable cacheUserRolesPermissions; - public UserRoleService(IAsbCloudDbContext db, CacheDb cacheDb) + public UserRoleService(IAsbCloudDbContext context, CacheDb cacheDb) : base(context) { - this.db = db; - cacheUserRoles = cacheDb.GetCachedTable((AsbCloudDbContext)db); - cachePermissions = cacheDb.GetCachedTable((AsbCloudDbContext)db); + cacheUserRoles = cacheDb.GetCachedTable((AsbCloudDbContext)context); + cachePermissions = cacheDb.GetCachedTable((AsbCloudDbContext)context); cacheUserRolesPermissions = - cacheDb.GetCachedTable((AsbCloudDbContext)db); + cacheDb.GetCachedTable((AsbCloudDbContext)context); } - public async Task> GetAllAsync(CancellationToken token) + public override async Task> GetAllAsync(CancellationToken token = default) { - var rolesDtos = (await cacheUserRoles.WhereAsync(token).ConfigureAwait(false)) - .Adapt(); + var rolesDtos = await base.GetAllAsync(token); return rolesDtos.Select(FillUserRoleWithPermissions); } - public async Task GetAsync(int id, CancellationToken token) + public override async Task GetAsync(int id, CancellationToken token = default) { - var roleDto = (await cacheUserRoles.FirstOrDefaultAsync(r => r.Id == id, token) - .ConfigureAwait(false)).Adapt(); + var roleDto = await base.GetAsync(id,token); return roleDto is null ? null : FillUserRoleWithPermissions(roleDto); } - public async Task InsertAsync(UserRoleDto dto, CancellationToken token = default) + public override async Task InsertAsync(UserRoleDto dto, CancellationToken token = default) { - var newRole = dto.Adapt(); - db.UserRoles.Add(newRole); - var result = await db.SaveChangesAsync(token); + var newRoleId = await base.InsertAsync(dto, token); if (dto.PermissionIds == default) - return result; + return newRoleId; foreach (var pId in dto.PermissionIds) { var relation = new RelationUserRolePermission() { - IdUserRole = newRole.Id, + IdUserRole = newRoleId, IdPermission = pId }; - db.RelationUserRolesPermissions.Add(relation); + context.RelationUserRolesPermissions.Add(relation); } - return await db.SaveChangesAsync(token); + return await context.SaveChangesAsync(token); } - public async Task UpdateAsync(UserRoleDto dto, CancellationToken token = default) + public override async Task UpdateAsync(int id, UserRoleDto item, CancellationToken token = default) { - var entity = dto.Adapt(); - db.UserRoles.Update(entity); - await db.SaveChangesAsync(token); + var result = await base.UpdateAsync(id, item, token); - if (dto.PermissionIds != default) + if (item.PermissionIds == default) + return result; + + await cacheUserRolesPermissions.RemoveAsync(r => r.IdUserRole == item.Id, token) + .ConfigureAwait(false); + + var newRelations = item.PermissionIds.Select(p => new RelationUserRolePermission() { - await cacheUserRolesPermissions.RemoveAsync(r => r.IdUserRole == dto.Id, token) - .ConfigureAwait(false); + IdUserRole = item.Id, + IdPermission = p + }); + await cacheUserRolesPermissions.InsertAsync(newRelations, token); - var newRelations = dto.PermissionIds.Select(p => new RelationUserRolePermission() - { - IdUserRole = dto.Id, - IdPermission = p - }); - await cacheUserRolesPermissions.InsertAsync(newRelations, token); - } - } - - public async Task DeleteAsync(IEnumerable ids, CancellationToken token) - { - var entities = cacheUserRoles.Where(e => ids.Contains(e.Id)); - if (entities == default) - return 0; - db.UserRoles.RemoveRange(entities); - return await db.SaveChangesAsync(token); + return result; } private UserRoleDto FillUserRoleWithPermissions(UserRoleDto roleDto) diff --git a/AsbCloudWebApi/Controllers/AdminUserRoleController.cs b/AsbCloudWebApi/Controllers/AdminUserRoleController.cs index d4dac698..c0325326 100644 --- a/AsbCloudWebApi/Controllers/AdminUserRoleController.cs +++ b/AsbCloudWebApi/Controllers/AdminUserRoleController.cs @@ -1,7 +1,4 @@ -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using AsbCloudApp.Data; +using AsbCloudApp.Data; using AsbCloudApp.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; @@ -11,93 +8,10 @@ namespace AsbCloudWebApi.Controllers [Route("api/admin/user/role")] [ApiController] [Authorize] - public class AdminUserRoleController : ControllerBase + public class AdminUserRoleController : CrudController> { - private readonly IUserRoleService userRoleService; - - public AdminUserRoleController(IUserRoleService userRoleService) - { - this.userRoleService = userRoleService; - } - - /// - /// Получает список всех доступных ролей - /// - /// Токен отмены задачи - /// Список всех доступных ролей - [HttpGet] - [ProducesResponseType(typeof(IEnumerable), (int)System.Net.HttpStatusCode.OK)] - public async Task GetAllAsync(CancellationToken token = default) - { - // TODO: Как будем делать проверку ролей пользователя? Админ, не админ. - - var result = await userRoleService.GetAllAsync(token) - .ConfigureAwait(false); - return Ok(result); - } - - /// - /// Получает информацию о запрашиваемой роли - /// - /// id запрашиваемой задачи - /// Токен отмены задачи - /// Информацию о запрашиваемой роли - [HttpGet("{idRole}")] - [ProducesResponseType(typeof(UserRoleDto), (int)System.Net.HttpStatusCode.OK)] - public async Task GetAsync(int idRole, CancellationToken token = default) - { - - var result = await userRoleService.GetAsync(idRole, token) - .ConfigureAwait(false); - return Ok(result); - } - - /// - /// Добавить запись - /// - /// Объект с параметрами добавляемой роли - /// Токен отмены задачи - /// 1 - добавлено, 0 - нет - [HttpPost] - [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)] - public async Task Insert([FromBody] UserRoleDto dto, - CancellationToken token = default) - { - var result = await userRoleService.InsertAsync(dto, token) - .ConfigureAwait(false); - return Ok(result); - } - - /// - /// Редактировать запись по id - /// - /// Объект с параметрами добавляемой роли - /// Id добавляемых к роли разрешений - /// - /// 1 - успешно отредактировано, 0 - нет - [HttpPut("{id}")] - [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)] - public async Task Update([FromBody] UserRoleDto dto, - CancellationToken token = default) - { - - await userRoleService.UpdateAsync(dto, token).ConfigureAwait(false); - return Ok(); - } - - /// - /// Удаляет роли по указанным id - /// - /// Список id ролей для удаления - /// - /// - [HttpDelete] - [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)] - public async Task Update(IEnumerable ids, CancellationToken token = default) - { - - var result = await userRoleService.DeleteAsync(ids, token).ConfigureAwait(false); - return Ok(result); - } + public AdminUserRoleController(ICrudService service) + : base(service) + { } } }