69 lines
2.1 KiB
Java
69 lines
2.1 KiB
Java
package ru.mtusi.messenger.validation;
|
|
|
|
import lombok.RequiredArgsConstructor;
|
|
|
|
import org.springframework.stereotype.Component;
|
|
|
|
import ru.mtusi.messenger.dto.CreateChatDTO;
|
|
import ru.mtusi.messenger.exception.InvalidRequestException;
|
|
import ru.mtusi.messenger.exception.NotFoundException;
|
|
import ru.mtusi.messenger.model.User;
|
|
import ru.mtusi.messenger.service.UserService;
|
|
|
|
import java.util.HashSet;
|
|
import java.util.List;
|
|
import java.util.Set;
|
|
import java.util.UUID;
|
|
|
|
@Component
|
|
@RequiredArgsConstructor
|
|
public class ChatValidator {
|
|
|
|
private final UserService userService;
|
|
|
|
public Set<User> validateCreate(UUID caller, CreateChatDTO createChatDTO) {
|
|
List<UUID> memberIds = createChatDTO.getMemberIds();
|
|
String title = createChatDTO.getTitle();
|
|
|
|
requireNotBlank(title, "Title must not be blank");
|
|
requireNonEmpty(memberIds, "member_ids must not be empty");
|
|
requireNoDuplicates(memberIds, "member_ids contains duplicates");
|
|
requireContains(memberIds, caller, "Вызывающий должен быть участником");
|
|
|
|
return requireAllUsersExist(memberIds);
|
|
}
|
|
|
|
private void requireNotBlank(String value, String message) {
|
|
if (value == null || value.trim().isEmpty()) {
|
|
throw new InvalidRequestException(message);
|
|
}
|
|
}
|
|
|
|
private void requireNonEmpty(List<UUID> ids, String message) {
|
|
if (ids == null || ids.isEmpty()) {
|
|
throw new InvalidRequestException(message);
|
|
}
|
|
}
|
|
|
|
private void requireNoDuplicates(List<UUID> ids, String message) {
|
|
Set<UUID> unique = new HashSet<>(ids);
|
|
if (unique.size() != ids.size()) {
|
|
throw new InvalidRequestException(message);
|
|
}
|
|
}
|
|
|
|
private void requireContains(List<UUID> ids, UUID value, String message) {
|
|
if (!ids.contains(value)) {
|
|
throw new InvalidRequestException(message);
|
|
}
|
|
}
|
|
|
|
private Set<User> requireAllUsersExist(List<UUID> ids) {
|
|
try {
|
|
return userService.requireUsers(ids);
|
|
} catch (NotFoundException e) {
|
|
throw new InvalidRequestException(e.getMessage());
|
|
}
|
|
}
|
|
}
|