Posts API stage 2: /posts/{id} is one post, drop userEmail and /posts/search

- GET /api/v1/posts/{id} returns a single post (owner-only for unpublished);
  /detail/{id} stays as an alias; user posts live at /api/v1/users/{userId}/posts
- POST /api/v1/posts Location points to /api/v1/posts/{id}
- PostResponse.userEmail removed (use userLogin); unused DialogResponse removed
- GET /api/v1/posts/search?city= removed (same filter: GET /api/v1/posts?city=)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
SlimusMinus
2026-10-21 00:03:39 +03:00
parent 13d09d0073
commit d782bee645
10 changed files with 59 additions and 112 deletions

View File

@@ -48,9 +48,8 @@ public class PostController {
public ResponseEntity<PostResponse> create(@Valid @ModelAttribute PostRequest request, @RequestParam(value = "images", required = false) List<MultipartFile> images) {
log.info("create post type={}, title='{}'", request.getType(), request.getTitle());
PostResponse created = service.create(request, images);
// Одно объявление пока отдаёт /detail/{id}; /posts/{id} поменяет смысл вторым этапом
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/detail/{id}").buildAndExpand(created.getId()).toUri();
.path("/{id}").buildAndExpand(created.getId()).toUri();
return ResponseEntity.created(location).body(created);
}
@@ -78,15 +77,14 @@ public class PostController {
}
/**
* Объявления ПОЛЬЗОВАТЕЛЯ с id {@code id} (историческое имя маршрута).
* Новый маршрут — GET /api/v1/users/{userId}/posts (постранично). Этот
* останется до деплоя фронта, затем /posts/{id} станет одним объявлением.
* Одно объявление. Неопубликованное (MODERATION, REJECTED) видит только
* владелец, остальным — 404. Объявления пользователя —
* GET /api/v1/users/{userId}/posts.
*/
@Deprecated
@GetMapping("/{id:\\d+}")
public List<PostResponse> getById(@PathVariable Long id) {
log.info("get feed by id {}", id);
return service.getPostsByUserId(id);
public PostResponse getById(@PathVariable Long id) {
log.info("get post by id {}", id);
return service.getPostById(id);
}
@PutMapping(value = "/{id}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@@ -111,25 +109,17 @@ public class PostController {
return service.updateStatus(id, request.getStatus());
}
/** Устарело: используйте GET /api/v1/posts?city= (лента с тем же фильтром). */
@Deprecated
@GetMapping("/search")
public Page<PostResponse> search(@RequestParam(required = false) String city,
@PageableDefault(size = 20, sort = "createdAt", direction = Sort.Direction.DESC) Pageable pageable) {
log.info("search posts by city {}", city);
return service.searchByCity(city, pageable);
}
@GetMapping("/cities")
public List<String> getCities() {
log.info("get distinct cities");
return service.getCities();
}
/** Прежний адрес одного объявления — алиас GET /api/v1/posts/{id}. */
@GetMapping("/detail/{postId}")
public PostResponse getPostOnMapById(@PathVariable Long postId) {
log.info("get post on map by id {}", postId);
return service.getPostOnMapById(postId);
public PostResponse getPostDetail(@PathVariable Long postId) {
log.info("get post detail {}", postId);
return service.getPostById(postId);
}
}

View File

@@ -1,15 +0,0 @@
package com.krylov.refound.dto;
import java.time.LocalDateTime;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class DialogResponse {
private Long userId;
private String userEmail;
private String lastMessage;
private LocalDateTime lastMessageTime;
private Long unreadCount;
}

View File

@@ -27,12 +27,6 @@ public class PostResponse {
private LocalDateTime createdAt;
/** Логин автора. */
private String userLogin;
/**
* Тот же логин под старым (ошибочным) именем — для клиентов, которые ещё
* читают userEmail. Удалить после перехода фронта на userLogin.
*/
@Deprecated
private String userEmail;
private String phone;
private List<String> images;
private Long userId;

View File

@@ -20,7 +20,6 @@ public interface PostMapper {
@Mapping(source = "user.id", target = "userId")
@Mapping(source = "user.login", target = "userLogin")
@Mapping(source = "user.login", target = "userEmail")
@Mapping(source = "images", target = "images", qualifiedByName = "imagesToUrls")
// Категория необязательна: без проверки на null пост без категории ронял ленту с 500
@Mapping(target = "category", expression = "java(post.getCategory() == null ? null : post.getCategory().getDisplayName())")

View File

@@ -17,8 +17,6 @@ import org.springframework.data.domain.Page;
public interface PostRepository extends JpaRepository<Post, Long>, JpaSpecificationExecutor<Post> {
List<Post> findByUserId(Long userId);
Page<Post> findByUserId(Long userId, Pageable pageable);
Page<Post> findByUserIdAndStatusIn(Long userId, Collection<PostStatus> statuses, Pageable pageable);

View File

@@ -56,7 +56,7 @@ import java.util.Set;
@Slf4j
public class PostService {
// Статусы, которые показываются в публичной ленте. MODERATION и REJECTED видны
// только владельцу (getPostsByUserId, getPostOnMapById), но не в общем фиде.
// только владельцу (getPostsByUser, getPostById), но не в общем фиде.
private static final Set<PostStatus> FEED_VISIBLE_STATUSES = PostVisibility.FEED_VISIBLE_STATUSES;
private final PostRepository postRepository;
@@ -190,13 +190,6 @@ public class PostService {
.toList();
}
/**
* Возвращает посты указанного пользователя (это НЕ поиск поста по его собственному id,
* несмотря на то, как метод назывался раньше — getById). Если у вас уже есть контроллер,
* вызывающий старое имя getById, переименуйте вызов на getPostsByUserId.
* Владелец видит все свои посты (включая MODERATION и REJECTED), остальные — только
* опубликованные (ACTIVE и CLOSED).
*/
/**
* Объявления пользователя постранично (GET /api/v1/users/{userId}/posts).
* Владелец видит все свои посты, остальные — только опубликованные.
@@ -209,22 +202,6 @@ public class PostService {
return posts.map(post -> toResponse(post, false));
}
public List<PostResponse> getPostsByUserId(Long userId) {
boolean owner = isCurrentUser(userId);
List<Post> posts = postRepository.findByUserId(userId).stream()
.filter(post -> owner || FEED_VISIBLE_STATUSES.contains(post.getStatus()))
.toList();
if (posts.isEmpty()) {
return List.of();
}
return posts.stream()
.map(post -> toResponse(post, false))
.toList();
}
/**
* Правка объявления владельцем; multipart-поля приходят по отдельности.
* Как и при создании, геокодер и загрузка фото выполняются до транзакции.
@@ -332,23 +309,6 @@ public class PostService {
return mapper.toResponse(updated);
}
/**
* Устаревший поиск по подстроке города/района — тот же фильтр есть в ленте
* (GET /api/v1/posts?city=). Оставлен на переходный период, уже постранично.
*/
@Deprecated
@Transactional(readOnly = true)
public Page<PostResponse> searchByCity(String city, Pageable pageable) {
if (!StringUtils.hasText(city)) {
return Page.empty(pageable);
}
Specification<Post> spec = Specification.where(PostSpecification.cityOrDistrictLike(city))
.and((root, query, cb) -> root.get("status").in(FEED_VISIBLE_STATUSES));
return postRepository.findAll(spec, pageable).map(post -> toResponse(post, true));
}
public List<String> getCities() {
return postRepository.findDistinctCities(FEED_VISIBLE_STATUSES);
}
@@ -482,7 +442,9 @@ public class PostService {
}
}
public PostResponse getPostOnMapById(Long postId) {
/** Одно объявление: GET /api/v1/posts/{id} (и алиас /detail/{id}). */
@Transactional(readOnly = true)
public PostResponse getPostById(Long postId) {
Post post = postRepository.findById(postId)
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "Post not found", HttpStatus.NOT_FOUND));

View File

@@ -60,15 +60,4 @@ public class PostSpecification {
cb.lower(root.get("district")).in(filter.cities()))
);
}
public static Specification<Post> cityOrDistrictLike(String query) {
if (!StringUtils.hasText(query)) {
return null;
}
String pattern = "%" + query.toLowerCase() + "%";
return (root, cq, cb) -> cb.or(
cb.like(cb.lower(root.get("city")), pattern),
cb.like(cb.lower(root.get("district")), pattern)
);
}
}

View File

@@ -7,7 +7,7 @@ import java.util.Set;
public final class PostVisibility {
// Статусы, видимые всем: в публичной ленте и на карте. MODERATION и REJECTED
// видны только владельцу поста (getPostsByUserId, getPostOnMapById в PostService)
// видны только владельцу поста (getPostsByUser, getPostById в PostService)
public static final Set<PostStatus> FEED_VISIBLE_STATUSES = EnumSet.of(PostStatus.ACTIVE, PostStatus.CLOSED);
private PostVisibility() {

View File

@@ -1,6 +1,7 @@
package com.krylov.refound.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
@@ -11,11 +12,13 @@ import com.krylov.refound.dto.PostResponse;
import com.krylov.refound.entity.Post;
import com.krylov.refound.entity.User;
import com.krylov.refound.enums.ErrorCode;
import com.krylov.refound.enums.PostStatus;
import com.krylov.refound.exception.ApiException;
import com.krylov.refound.mapper.PostMapper;
import com.krylov.refound.repository.PostRepository;
import com.krylov.refound.util.PostVisibility;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
@@ -73,6 +76,37 @@ class PostServiceUserPostsTest {
verify(postRepository, never()).findByUserId(5L, pageable);
}
@Test
void singlePostUnderModerationIsHiddenFromOthers() {
User owner = new User();
owner.setId(5L);
Post post = new Post();
post.setUser(owner);
post.setStatus(PostStatus.MODERATION);
when(postRepository.findById(7L)).thenReturn(Optional.of(post));
when(userService.getCurrentUser())
.thenThrow(new ApiException(ErrorCode.UNAUTHORIZED, "Unauthorized", HttpStatus.UNAUTHORIZED));
assertThatThrownBy(() -> service.getPostById(7L))
.isInstanceOfSatisfying(ApiException.class,
e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.NOT_FOUND));
}
@Test
void singlePostUnderModerationIsVisibleToOwner() {
User owner = new User();
owner.setId(5L);
Post post = new Post();
post.setUser(owner);
post.setStatus(PostStatus.MODERATION);
when(postRepository.findById(7L)).thenReturn(Optional.of(post));
when(userService.getCurrentUser()).thenReturn(owner);
PostResponse dto = new PostResponse();
when(mapper.toResponse(post)).thenReturn(dto);
assertThat(service.getPostById(7L)).isSameAs(dto);
}
@Test
void anonymousGetsOnlyPublishedPosts() {
when(userService.getCurrentUser())