/// <summary> /// Creates a new animal and stores it in the database. In addition /// it finds current user and stores the current user as the animal's creator. /// </summary> /// <param name="model"></param> /// <returns>animal's id</returns> public async Task <int> CreateAnimal(AnimalBm model) { var animal = mapper.Map <Animal>(model); var userId = GetCurrentUser(); animal.UserId = userId; // will be better to put in constructor of DTO or Bm animal.CreatedAt = DateTime.Now; animal.UpdatedAt = DateTime.Now; var userAnimals = await context.Animals.Where(x => x.UserId == userId) .FirstOrDefaultAsync(x => x.Name == model.Name); if (userAnimals == null) { context.Add(animal); await context.SaveChangesAsync(); var animalLocation = mapper.Map <LocationBm>(model); animalLocation.AnimalId = animal.Id; await locationRepository.CreateLocation(animalLocation); logger.LogInfo($"Animal with id {animal.Id} successfully created."); return(animal.Id); } else { throw new BadRequestException($"You already registered an animal with the same name."); } }
/// <summary> /// Finds an animal by its id and then updates it with the model /// parameter. If the animal can not be found the method throws /// a 404 Not Found. /// </summary> /// <param name="model"></param> /// <param name="id"></param> /// <returns></returns> public async Task <int> UpdateAnimal(AnimalBm model, int id) { var animal = await GetAnimalData(id); // will be better to put in constructor of DTO or Bm animal.UpdatedAt = DateTime.Now; if (animal != null) { animal = mapper.Map(model, animal); context.Update(animal); await context.SaveChangesAsync(); var animalLocation = mapper.Map <LocationBm>(model); animalLocation.AnimalId = animal.Id; await locationRepository.UpdateLocation(animalLocation); logger.LogInfo($"Animal with id {id} successfully updated."); return(id); } else { throw new NotFoundException($"Animal with id {id} does not exist."); } }
public async Task <IActionResult> UpdateAnimal([FromBody] AnimalBm model, [FromRoute] int id) { var result = await AnimalsService.UpdateAnimal(model, id); return(Ok(result)); }
public async Task <IActionResult> CreateAnimal([FromBody] AnimalBm model) { var result = await AnimalsService.CreateAnimal(model); return(Ok(result)); }