diff --git a/3-Domain/src/main/java/category/CategoryPersistenceAdapter.java b/3-Domain/src/main/java/category/CategoryPersistenceAdapter.java new file mode 100644 index 0000000..75783e8 --- /dev/null +++ b/3-Domain/src/main/java/category/CategoryPersistenceAdapter.java @@ -0,0 +1,10 @@ +package category; + +import java.util.Set; + +public interface CategoryPersistenceAdapter { + + Set getAll(); + Boolean add(Category category); + +} diff --git a/3-Domain/src/main/java/category/CategoryRepository.java b/3-Domain/src/main/java/category/CategoryRepository.java new file mode 100644 index 0000000..dde235f --- /dev/null +++ b/3-Domain/src/main/java/category/CategoryRepository.java @@ -0,0 +1,47 @@ +package category; + +import exeptions.CategoryAlreadyExists; +import exeptions.NonUniqueId; + +import java.util.Optional; +import java.util.Set; + +public class CategoryRepository { + + final private CategoryPersistenceAdapter categoryPersistenceAdapter; + final private Set categories; + + public CategoryRepository(CategoryPersistenceAdapter categoryPersistenceAdapter) { + this.categoryPersistenceAdapter = categoryPersistenceAdapter; + this.categories = categoryPersistenceAdapter.getAll(); + } + + public Optional getByName(CategoryName name) { + return categories.stream().filter(category -> category.getName().equals(name)).findFirst(); + } + + public Optional getById(CategoryId id) { + return categories.stream().filter(category -> category.getId().equals(id)).findFirst(); + } + + public Set getAll(){ + return categories; + } + + public void add(Category category) { + checkDuplicates(category); + + categories.add(category); + categoryPersistenceAdapter.add(category); + } + + private void checkDuplicates(Category category) { + if (this.getByName(category.getName()).isPresent()) { + throw new CategoryAlreadyExists("A category with the name " + category.getName() + " already exits."); + } + + if (this.getById(category.getId()).isPresent()) { + throw new NonUniqueId("A category with the id " + category.getId() + " already exits."); + } + } +} diff --git a/3-Domain/src/main/java/exeptions/CategoryAlreadyExists.java b/3-Domain/src/main/java/exeptions/CategoryAlreadyExists.java new file mode 100644 index 0000000..614707a --- /dev/null +++ b/3-Domain/src/main/java/exeptions/CategoryAlreadyExists.java @@ -0,0 +1,8 @@ +package exeptions; + +public class CategoryAlreadyExists extends RuntimeException { + + public CategoryAlreadyExists(String message) { + super(message); + } +} diff --git a/3-Domain/src/main/java/exeptions/NonUniqueId.java b/3-Domain/src/main/java/exeptions/NonUniqueId.java new file mode 100644 index 0000000..e710e05 --- /dev/null +++ b/3-Domain/src/main/java/exeptions/NonUniqueId.java @@ -0,0 +1,8 @@ +package exeptions; + +public class NonUniqueId extends RuntimeException { + + public NonUniqueId(String message) { + super(message); + } +}