Add Category Adapter
This commit is contained in:
parent
325adfb0f2
commit
f003a9a5e2
|
@ -0,0 +1,10 @@
|
|||
package category;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
public interface CategoryPersistenceAdapter {
|
||||
|
||||
Set<Category> getAll();
|
||||
Boolean add(Category category);
|
||||
|
||||
}
|
47
3-Domain/src/main/java/category/CategoryRepository.java
Normal file
47
3-Domain/src/main/java/category/CategoryRepository.java
Normal file
|
@ -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<Category> categories;
|
||||
|
||||
public CategoryRepository(CategoryPersistenceAdapter categoryPersistenceAdapter) {
|
||||
this.categoryPersistenceAdapter = categoryPersistenceAdapter;
|
||||
this.categories = categoryPersistenceAdapter.getAll();
|
||||
}
|
||||
|
||||
public Optional<Category> getByName(CategoryName name) {
|
||||
return categories.stream().filter(category -> category.getName().equals(name)).findFirst();
|
||||
}
|
||||
|
||||
public Optional<Category> getById(CategoryId id) {
|
||||
return categories.stream().filter(category -> category.getId().equals(id)).findFirst();
|
||||
}
|
||||
|
||||
public Set<Category> 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.");
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
package exeptions;
|
||||
|
||||
public class CategoryAlreadyExists extends RuntimeException {
|
||||
|
||||
public CategoryAlreadyExists(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
8
3-Domain/src/main/java/exeptions/NonUniqueId.java
Normal file
8
3-Domain/src/main/java/exeptions/NonUniqueId.java
Normal file
|
@ -0,0 +1,8 @@
|
|||
package exeptions;
|
||||
|
||||
public class NonUniqueId extends RuntimeException {
|
||||
|
||||
public NonUniqueId(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
Reference in a new issue