Add Category Adapter

This commit is contained in:
qvalentin 2022-04-01 17:07:24 +02:00
parent 325adfb0f2
commit f003a9a5e2
Signed by: qvalentin
GPG Key ID: C979FA1EAFCABF1C
4 changed files with 73 additions and 0 deletions

View File

@ -0,0 +1,10 @@
package category;
import java.util.Set;
public interface CategoryPersistenceAdapter {
Set<Category> getAll();
Boolean add(Category category);
}

View 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.");
}
}
}

View File

@ -0,0 +1,8 @@
package exeptions;
public class CategoryAlreadyExists extends RuntimeException {
public CategoryAlreadyExists(String message) {
super(message);
}
}

View File

@ -0,0 +1,8 @@
package exeptions;
public class NonUniqueId extends RuntimeException {
public NonUniqueId(String message) {
super(message);
}
}