From 6a85255c78a448256fab68cd361983ffc85f2b03 Mon Sep 17 00:00:00 2001 From: transtrike Date: Fri, 11 Dec 2020 14:35:39 +0200 Subject: Renamed Models to Data --- API/Service/UserService.cs | 39 ++++++++++++++++++++++++++++----------- 1 file changed, 28 insertions(+), 11 deletions(-) (limited to 'API/Service') diff --git a/API/Service/UserService.cs b/API/Service/UserService.cs index d32b31f..a03de45 100644 --- a/API/Service/UserService.cs +++ b/API/Service/UserService.cs @@ -2,10 +2,14 @@ using System.Net; using System.Threading.Tasks; using API.Database; using AutoMapper; -using Models.Classes; -using Models.DTOs; +using Data.Models.Classes; +using Data.Models.DTOs; using Newtonsoft.Json; using System.Web.Http; +using System.Net.Http; +using Npgsql.EntityFrameworkCore.PostgreSQL.Query.ExpressionTranslators.Internal; +using System; +using Microsoft.AspNetCore.Mvc.Routing; namespace API.Service { @@ -22,30 +26,32 @@ namespace API.Service public async Task CreateUser(UserDTO userDTO) { - if(this._userDbRepository.DoesUsernameExist(userDTO.UserName)) - return HttpStatusCode.Forbidden; + if (this._userDbRepository.DoesUsernameExist(userDTO.UserName)) + ThrowHttpRequestException(HttpStatusCode.BadRequest, "Username already exists!"); User user = this._userMapper.Map(userDTO); await this._userDbRepository.AddAsync(user); - return HttpStatusCode.OK; + return HttpStatusCode.Created; } - public async Task GetUserById(int id) + public async Task GetUserById(int id) { - User user = await this._userDbRepository.FindByIdAsync(id) ?? - throw new HttpResponseException(HttpStatusCode.NotFound); + User user = await this._userDbRepository.FindByIdAsync(id); - return JsonConvert.SerializeObject(user); + if (user == null) + ThrowHttpRequestException(HttpStatusCode.NotFound); + + return user; } public async Task UpdateUser(int id, UserDTO userDTO) { if (!this._userDbRepository.DoesUserExist(id)) - return HttpStatusCode.NotFound; + ThrowHttpRequestException(HttpStatusCode.NotFound); if (this._userDbRepository.DoesUsernameExist(userDTO.UserName)) - return HttpStatusCode.Forbidden; + ThrowHttpRequestException(HttpStatusCode.Forbidden); User user = this._userMapper.Map(userDTO); await this._userDbRepository.EditAsync(id, user); @@ -62,5 +68,16 @@ namespace API.Service return HttpStatusCode.OK; } + + private void ThrowHttpRequestException(HttpStatusCode statusCode, string errorMessage = "") + { + HttpResponseMessage message = new() + { + StatusCode = statusCode, + Content = new StringContent(errorMessage) + }; + + throw new HttpResponseException(message); + } } } -- cgit v1.2.3