aboutsummaryrefslogtreecommitdiff
path: root/src/DevHive.Services/Services/RoleService.cs
blob: c0b90624fac0ff59f30595eb1913be16c1032e3a (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
using System;
using System.Threading.Tasks;
using AutoMapper;
using DevHive.Common.Models.Identity;
using DevHive.Data.Models;
using DevHive.Data.Repositories;

namespace DevHive.Services.Services
{
	public class RoleService
	{
		private readonly RoleRepository _roleRepository;
		private readonly IMapper _roleMapper;

		public RoleService(DevHiveContext context, IMapper mapper)
		{
			this._roleRepository = new RoleRepository(context);
			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);
		}
	}
}