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:
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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())")
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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));
|
||||
|
||||
|
||||
@@ -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)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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() {
|
||||
|
||||
Reference in New Issue
Block a user