public static Model.TroublePatchInfo Convert(string id, Client.TroublePatchInfo clientPatchInfo, IReadOnlyList <Models.Tags.Tag> modelTags) { if (clientPatchInfo == null) { throw new ArgumentNullException(nameof(clientPatchInfo)); } if (modelTags == null) { throw new ArgumentNullException(nameof(modelTags)); } string[] filteredTagIds = null; if (clientPatchInfo.Tags != null) { filteredTagIds = TroubleConverterUtils.FilterWrongTagIds(clientPatchInfo.Tags, modelTags).ToArray(); if (!filteredTagIds.Any()) { throw new InvalidDataException($"{nameof(filteredTagIds)} can't be empty."); } } double?latitude = null, longitude = null; if (clientPatchInfo.Coordinates != null) { if (clientPatchInfo.Coordinates.Count != CoordinatesLength) { throw new InvalidDataException( $"{nameof(clientPatchInfo.Coordinates)} must contain 2 values (lat and long)."); } latitude = clientPatchInfo.Coordinates[0]; longitude = clientPatchInfo.Coordinates[1]; } var guid = TroubleConverterUtils.ConvertId(id); var status = TroubleConverterUtils.ConvertStatus(clientPatchInfo.Status); var modelPathInfo = new Models.Troubles.TroublePatchInfo(guid) { Name = clientPatchInfo.Name, Description = clientPatchInfo.Description, Images = clientPatchInfo.Images, Latitude = latitude, Longitude = longitude, Address = clientPatchInfo.Address, Tags = filteredTagIds, Status = status }; return(modelPathInfo); }
public async Task <IActionResult> PatchTroubleAsync([FromRoute] string id, [FromBody] Client.TroublePatchInfo patchInfo, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (patchInfo == null) { var error = Responses.BodyIsMissing(nameof(patchInfo)); return(BadRequest(error)); } var guid = Converter.TroubleConverterUtils.ConvertId(id); Model.Trouble trouble; try { trouble = await troubleRepository.GetAsync(guid, cancellationToken).ConfigureAwait(false); } catch (TroubleNotFoundException ex) { var error = Responses.NotFoundError(ex.Message, Target); return(BadRequest(error)); } var isAuthorized = trouble.Author == HttpContext.User.Identity.Name || HttpContext.User.IsInRole("admin"); if (!isAuthorized) { return(Forbid()); } if (!HttpContext.User.IsInRole("admin")) { patchInfo.Status = null; } Model.Trouble modelTrouble; try { var modelTags = await tagRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); var modelPatchInfo = Converter.TroublePatchInfoConverter.Convert(id, patchInfo, modelTags); modelTrouble = await troubleRepository.PatchAsync(modelPatchInfo, cancellationToken).ConfigureAwait(false); } catch (Exception ex) { if (ex is TroubleNotFoundException) { var error = Responses.NotFoundError(ex.Message, Target); return(BadRequest(error)); } else { var error = Responses.InvalidData(ex.Message, Target); return(BadRequest(error)); } } var clientTrouble = Converter.TroubleConverter.Convert(modelTrouble); return(Ok(clientTrouble)); }