|
| 1 | +package com.udacity.doggraphqlapi.mutator; |
| 2 | + |
| 3 | +import java.util.Optional; |
| 4 | + |
| 5 | +import org.springframework.stereotype.Component; |
| 6 | + |
| 7 | +import com.coxautodev.graphql.tools.GraphQLMutationResolver; |
| 8 | +import com.udacity.doggraphqlapi.entity.Dog; |
| 9 | +import com.udacity.doggraphqlapi.repository.DogRepository; |
| 10 | + |
| 11 | +@Component |
| 12 | +public class Mutation implements GraphQLMutationResolver { |
| 13 | + private DogRepository dogRepository; |
| 14 | + |
| 15 | + public Mutation(DogRepository dogRepository) {this.dogRepository = dogRepository; } |
| 16 | + |
| 17 | + public Dog newDog(String name, String breed) { |
| 18 | + Dog dog = new Dog(name, breed); |
| 19 | + dogRepository.save(dog); |
| 20 | + return dog; |
| 21 | + } |
| 22 | + |
| 23 | + public boolean deleteDog(Long id) { |
| 24 | + dogRepository.deleteById(id); |
| 25 | + return true; |
| 26 | + } |
| 27 | + |
| 28 | + public boolean deleteDogBreed(String breed) { |
| 29 | + boolean deleted = false; |
| 30 | + Iterable<Dog> allDogs = dogRepository.findAll(); |
| 31 | + // Loop through all dogs to check their breed |
| 32 | + for (Dog d:allDogs) { |
| 33 | + if (d.getBreed().equals(breed)) { |
| 34 | + // Delete if the breed is found |
| 35 | + dogRepository.delete(d); |
| 36 | + deleted = true; |
| 37 | + } |
| 38 | + } |
| 39 | + // Throw an exception if the breed doesn't exist |
| 40 | + if (!deleted) { |
| 41 | + throw new BreedNotFoundException("Breed Not Found", breed); |
| 42 | + } |
| 43 | + return deleted; |
| 44 | + } |
| 45 | + |
| 46 | + public Dog updateDogName(String newName, Long id) { |
| 47 | + Optional<Dog> optionalDog = dogRepository.findById(id); |
| 48 | + if (optionalDog.isPresent()) { |
| 49 | + Dog dog = optionalDog.get(); |
| 50 | + // Set the new name and save the updated dog |
| 51 | + dog.setName(newName); |
| 52 | + dogRepository.save(dog); |
| 53 | + return dog; |
| 54 | + } else { |
| 55 | + throw new DogNotFoundException("Dog Not Found", id); |
| 56 | + } |
| 57 | + |
| 58 | + } |
| 59 | +} |
0 commit comments