Ejemplo n.º 1
0
        [HttpPost("{id}/setMain")] // typically simple updates for restful apis are of type put or patch but post is conveniet
        public async Task<IActionResult> SetMainPhoto(int userId, int id) { 

            // authorization
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)){
                return Unauthorized();
            }

            // getting the user
            var userFromRepo = await _repo.GetUser(userId);

            if (!userFromRepo.Photos.Any(p => p.Id == id)) { // we can only update the photo if he has that photo 
                return Unauthorized();
            }

            var photoFromRepo = await _repo.GetPhoto(id);

            if (photoFromRepo.IsMain) {
                return BadRequest("This is already the main photo");
            }

            var currentMainPhoto = await _repo.GetMainPhoto(userId);

            currentMainPhoto.IsMain = false;
            photoFromRepo.IsMain = true;

            if(await _repo.SaveAll()) { 
                return NoContent();
            }

            return BadRequest("Unable to set photo to main");
        }