aboutsummaryrefslogtreecommitdiff
path: root/src/Services/DevHive.Services/Services/RoleService.cs
blob: f61181aa498aa97b71f313df6a77ce6278312111 (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
62
63
64
65
66
67
68
69
70
71
using System;
using System.Data;
using System.Threading.Tasks;
using AutoMapper;
using DevHive.Common.Constants;
using DevHive.Data.Interfaces;
using DevHive.Data.Models;
using DevHive.Services.Interfaces;
using DevHive.Services.Models.Role;

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<Guid> CreateRole(CreateRoleServiceModel createRoleServiceModel)
		{
			if (await this._roleRepository.DoesNameExist(createRoleServiceModel.Name))
				throw new DuplicateNameException(string.Format(ErrorMessages.AlreadyExists, ClassesConstants.Role));

			Role role = this._roleMapper.Map<Role>(createRoleServiceModel);
			bool success = await this._roleRepository.AddAsync(role);

			if (success)
			{
				Role newRole = await this._roleRepository.GetByNameAsync(createRoleServiceModel.Name);
				return newRole.Id;
			}
			else
				return Guid.Empty;

		}

		public async Task<RoleServiceModel> GetRoleById(Guid id)
		{
			Role role = await this._roleRepository.GetByIdAsync(id) ??
				throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Role));

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

		public async Task<bool> UpdateRole(UpdateRoleServiceModel updateRoleServiceModel)
		{
			if (!await this._roleRepository.DoesRoleExist(updateRoleServiceModel.Id))
				throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Role));

			if (await this._roleRepository.DoesNameExist(updateRoleServiceModel.Name))
				throw new DuplicateNameException(string.Format(ErrorMessages.AlreadyExists, ClassesConstants.Role));

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

		public async Task<bool> DeleteRole(Guid id)
		{
			if (!await this._roleRepository.DoesRoleExist(id))
				throw new ArgumentNullException(string.Format(ErrorMessages.DoesNotExist, ClassesConstants.Role));

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