aboutsummaryrefslogtreecommitdiff
path: root/src/DevHive.Services/Services/RoleService.cs
blob: fd56c2c5fd40d5c7a591d46021e1fe5781947b42 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
using System;
using System.Threading.Tasks;
using AutoMapper;
using DevHive.Common.Models.Identity;
using DevHive.Data.Interfaces;
using DevHive.Data.Models;
using DevHive.Services.Interfaces;

namespace DevHive.Services.Services
{
	public class RoleService : IRoleService
	{
		private readonly IRoleRepository _roleRepository;
		private readonly IMapper _roleMapper;

		public RoleService(IRoleRepository roleRepository, IMapper mapper)
		{
			this._roleRepository = roleRepository;
			this._roleMapper = mapper;
		}

		public async Task<bool> CreateRole(RoleModel roleServiceModel)
		{
			if (await this._roleRepository.DoesNameExist(roleServiceModel.Name))
				throw new ArgumentException("Role already exists!");

			Role role = this._roleMapper.Map<Role>(roleServiceModel);

			return await this._roleRepository.AddAsync(role);
		}

		public async Task<RoleModel> GetRoleById(Guid id)
		{
			Role role = await this._roleRepository.GetByIdAsync(id)
				?? throw new ArgumentException("Role does not exist!");

			return this._roleMapper.Map<RoleModel>(role);
		}

		public async Task<bool> UpdateRole(RoleModel roleServiceModel)
		{
			if (!await this._roleRepository.DoesRoleExist(roleServiceModel.Id))
				throw new ArgumentException("Role does not exist!");

			if (await this._roleRepository.DoesNameExist(roleServiceModel.Name))
				throw new ArgumentException("Role name already exists!");

			Role role = this._roleMapper.Map<Role>(roleServiceModel);
			return await this._roleRepository.EditAsync(role);
		}

		public async Task<bool> DeleteRole(Guid id)
		{
			if (!await this._roleRepository.DoesRoleExist(id))
				throw new ArgumentException("Role does not exist!");

			Role role = await this._roleRepository.GetByIdAsync(id);
			return await this._roleRepository.DeleteAsync(role);
		}
	}
}