aboutsummaryrefslogtreecommitdiff
path: root/src/Web/DevHive.Web/Controllers/RatingController.cs
blob: 33e699230986e2617e003caf177d5ac1e239a491 (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
72
73
74
75
using System;
using System.Threading.Tasks;
using AutoMapper;
using DevHive.Services.Interfaces;
using DevHive.Services.Models.Post.Rating;
using DevHive.Web.Models.Rating;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace DevHive.Web.Controllers
{
	[ApiController]
	//[Authorize(Roles = "Admin,User")]
	[Route("api/[controller]")]
	public class RatingController
	{
		private readonly IRatingService _rateService;
		private readonly IUserService _userService;
		private readonly IMapper _mapper;

		public RatingController(IRatingService rateService, IUserService userService, IMapper mapper)
		{
			this._rateService = rateService;
			this._userService = userService;
			this._mapper = mapper;
		}

		[HttpPost]
		public async Task<IActionResult> RatePost(Guid userId, [FromBody] CreateRatingWebModel createRatingWebModel, [FromHeader] string authorization)
		{
			if (!await this._rateService.ValidateJwtForCreating(userId, authorization))
				return new UnauthorizedResult();

			CreateRatingServiceModel ratePostServiceModel = this._mapper.Map<CreateRatingServiceModel>(createRatingWebModel);
			ratePostServiceModel.UserId = userId;

			Guid id = await this._rateService.RatePost(ratePostServiceModel);

			if (Guid.Empty == id)
				return new BadRequestResult();

			return new OkObjectResult(new { Id = id });
		}

		[HttpGet]
		public async Task<IActionResult> GetRatingById(Guid id)
		{
			ReadRatingServiceModel readRatingServiceModel = await this._rateService.GetRatingById(id);
			ReadRatingWebModel readPostRatingWebModel = this._mapper.Map<ReadRatingWebModel>(readRatingServiceModel);

			return new OkObjectResult(readPostRatingWebModel);
		}

		[HttpPut]
		public async Task<IActionResult> UpdateRating(Guid userId, [FromBody] UpdateRatingWebModel updateRatingWebModel, [FromHeader] string authorization)
		{
			if (!await this._rateService.ValidateJwtForRating(updateRatingWebModel.Id, authorization))
				return new UnauthorizedResult();

			UpdateRatingServiceModel updateRatingServiceModel =
				this._mapper.Map<UpdateRatingServiceModel>(updateRatingWebModel);
			updateRatingServiceModel.UserId = userId;

			ReadRatingServiceModel readRatingServiceModel = await this._rateService.UpdateRating(updateRatingServiceModel);

			if (readRatingServiceModel == null)
				return new BadRequestResult();
			else
			{
				ReadRatingWebModel readRatingWebModel = this._mapper.Map<ReadRatingWebModel>(readRatingServiceModel);
				return new OkObjectResult(readRatingWebModel);
			}
		}
	}
}