Posts API: user posts page, 201 on create, userLogin, deprecate old routes
- GET /api/v1/users/{userId}/posts returns Page<PostResponse> (owner sees unpublished)
- POST /api/v1/posts returns 201 with the created PostResponse and Location
- PostResponse.userLogin; userEmail kept with the same value as deprecated
- GET /api/v1/posts/{userId} and /search?city= marked deprecated; search is paged
- CORS exposes Retry-After and Location to the frontend
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
20
README.MD
20
README.MD
@@ -334,6 +334,7 @@ DTO (MapStruct / ручной маппинг) → JSON; ошибки → GlobalE
|
||||
### 7.4 CORS и загрузка файлов
|
||||
|
||||
- CORS для REST — `CORS_ALLOWED_ORIGINS` (с credentials, методы GET/POST/PUT/DELETE/PATCH/OPTIONS).
|
||||
Фронту открыты заголовки ответа `Retry-After` и `Location` (`Access-Control-Expose-Headers`).
|
||||
- WebSocket-эндпоинт `/ws` разрешает любые origin: токен передаётся в STOMP-заголовке,
|
||||
а не в cookie, поэтому чужая страница не получит доступ без токена.
|
||||
- Картинки: ≤ 10 МБ, JPEG/PNG/WebP — и по `Content-Type`, и по сигнатуре
|
||||
@@ -387,21 +388,21 @@ DTO (MapStruct / ручной маппинг) → JSON; ошибки → GlobalE
|
||||
|
||||
| Метод и путь | Что делает |
|
||||
|---|---|
|
||||
| `POST /` (multipart: поля `PostRequest` + `images[]`) | создать; статус `MODERATION`. Возвращает присланный `PostRequest` |
|
||||
| `POST /` (multipart: поля `PostRequest` + `images[]`) | создать; статус `MODERATION`. Ответ — **201** с созданным `PostResponse` и `Location: /api/v1/posts/detail/{id}` |
|
||||
| `GET /?search=&type=&category=&city=` | лента `Page<PostResponse>` (ACTIVE и CLOSED); с `search` — поиск по релевантности |
|
||||
| `GET /search/suggest?q=` | подсказки для последнего слова |
|
||||
| `GET /{userId}` | **объявления пользователя** с id `userId` (своему — включая неопубликованные) |
|
||||
| `GET /{userId}` | **устарело**: объявления пользователя списком. Замена — `GET /api/v1/users/{userId}/posts`; после перехода фронта маршрут станет «одно объявление» (сейчас это `/detail/{postId}`) |
|
||||
| `GET /detail/{postId}` | одно объявление |
|
||||
| `PUT /{id}` (multipart: `type, title, address, latitude, longitude, description, category, phone, reward, rewardText, images[], existingImages`) | правка владельцем; снова `MODERATION`. `existingImages` — JSON-массив ключей картинок, которые остаются |
|
||||
| `PATCH /{id}/status` `{status}` | владелец переводит опубликованное объявление в `ACTIVE`/`CLOSED` |
|
||||
| `DELETE /{id}` | удаление владельцем (с избранным, ссылками чатов и файлами) |
|
||||
| `GET /search?city=` | объявления по подстроке города/района (без пагинации) |
|
||||
| `GET /search?city=` | **устарело**: объявления по подстроке города/района, `Page<PostResponse>`. Тот же фильтр — `GET /?city=` |
|
||||
| `GET /cities` | список городов опубликованных объявлений |
|
||||
| `GET /map?minLat=&maxLat=&minLng=&maxLng=&type=&category=` | метки карты |
|
||||
|
||||
`PostResponse`: `id, title, description, category (название), city, district,
|
||||
address, latitude, longitude, type, status, createdAt, userEmail (логин
|
||||
автора), phone, images (ключи файлов), userId, userRole, rulesAccepted,
|
||||
address, latitude, longitude, type, status, createdAt, userLogin (логин
|
||||
автора; `userEmail` — то же значение, устаревшее имя), phone, images (ключи файлов), userId, userRole, rulesAccepted,
|
||||
reward, rewardText`.
|
||||
|
||||
Ограничения полей: `title` обязателен, ≤ 255; `address` ≤ 500; `phone`,
|
||||
@@ -423,6 +424,7 @@ reward, rewardText`.
|
||||
|
||||
| Метод и путь | Что делает |
|
||||
|---|---|
|
||||
| `GET /api/v1/users/{userId}/posts?page=&size=` | объявления пользователя, `Page<PostResponse>` (публично; владельцу — включая неопубликованные) |
|
||||
| `GET /api/v1/users/{id}` | профиль `{id, login, name, lastName, phone, email, avatar, role}`; `phone` и `email` — только своему профилю и админу, остальным `null` |
|
||||
| `PUT /api/v1/users/{id}` (multipart: `login, firstName, lastName, phone, email, avatar, removeAvatar`) | правка своего профиля; пустой `login` не меняет логин. Если пользователь сменил свой логин, в ответе есть новые `token` и `refreshToken` — клиент должен их сохранить (старые больше не действуют) |
|
||||
| `POST /api/v1/favorites/{postId}/toggle` | добавить/убрать из избранного |
|
||||
@@ -640,10 +642,10 @@ Redis и MinIO в тестах не нужны: в профиле `test` MinIO
|
||||
|
||||
Что остаётся и требует решения или отдельной задачи:
|
||||
|
||||
- **API-контракт** (менять вместе с фронтендом): `GET /api/v1/posts/{id}`
|
||||
возвращает объявления пользователя, а не объявление; `POST /api/v1/posts`
|
||||
возвращает эхо запроса; поле `userEmail` содержит логин;
|
||||
`GET /api/v1/posts/search?city=` без пагинации.
|
||||
- **API-контракт, второй этап** (после деплоя фронта, который ходит на
|
||||
`/users/{userId}/posts` и читает `userLogin`): `GET /api/v1/posts/{id}`
|
||||
должен отдавать одно объявление (`/detail/{id}` оставить алиасом), убрать
|
||||
`userEmail` из `PostResponse` и `GET /api/v1/posts/search`.
|
||||
- **Фронт должен подхватить** новые поля: `impressionToken` в ответе
|
||||
`/api/ads/next` (вернуть в `/impression` и `/click`, затем включить
|
||||
`ADS_REQUIRE_TRACKING_TOKEN`), `token`/`refreshToken` в ответе правки профиля
|
||||
|
||||
@@ -18,6 +18,9 @@ import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.web.PageableDefault;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import java.net.URI;
|
||||
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
@@ -40,10 +43,15 @@ public class PostController {
|
||||
private final PostService service;
|
||||
private final SearchSuggestService searchSuggestService;
|
||||
|
||||
/** 201 с созданным объявлением и Location на него (раньше — эхо PostRequest). */
|
||||
@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
public PostRequest create(@Valid @ModelAttribute PostRequest request, @RequestParam(value = "images", required = false) List<MultipartFile> images) {
|
||||
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());
|
||||
return service.create(request, images);
|
||||
PostResponse created = service.create(request, images);
|
||||
// Одно объявление пока отдаёт /detail/{id}; /posts/{id} поменяет смысл вторым этапом
|
||||
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
|
||||
.path("/detail/{id}").buildAndExpand(created.getId()).toUri();
|
||||
return ResponseEntity.created(location).body(created);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
@@ -69,6 +77,12 @@ public class PostController {
|
||||
return searchSuggestService.suggest(query);
|
||||
}
|
||||
|
||||
/**
|
||||
* Объявления ПОЛЬЗОВАТЕЛЯ с id {@code id} (историческое имя маршрута).
|
||||
* Новый маршрут — GET /api/v1/users/{userId}/posts (постранично). Этот
|
||||
* останется до деплоя фронта, затем /posts/{id} станет одним объявлением.
|
||||
*/
|
||||
@Deprecated
|
||||
@GetMapping("/{id:\\d+}")
|
||||
public List<PostResponse> getById(@PathVariable Long id) {
|
||||
log.info("get feed by id {}", id);
|
||||
@@ -97,10 +111,13 @@ public class PostController {
|
||||
return service.updateStatus(id, request.getStatus());
|
||||
}
|
||||
|
||||
/** Устарело: используйте GET /api/v1/posts?city= (лента с тем же фильтром). */
|
||||
@Deprecated
|
||||
@GetMapping("/search")
|
||||
public List<PostResponse> search(@RequestParam(required = false) String city) {
|
||||
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);
|
||||
return service.searchByCity(city, pageable);
|
||||
}
|
||||
|
||||
@GetMapping("/cities")
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.krylov.refound.controller;
|
||||
|
||||
import com.krylov.refound.dto.PostResponse;
|
||||
import com.krylov.refound.service.PostService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.web.PageableDefault;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* Объявления пользователя: GET /api/v1/users/{userId}/posts. Публичный —
|
||||
* владельцу (с токеном) отдаются и неопубликованные (MODERATION, REJECTED).
|
||||
*/
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
public class UserPostController {
|
||||
|
||||
private final PostService postService;
|
||||
|
||||
@GetMapping("/api/v1/users/{userId:\\d+}/posts")
|
||||
public Page<PostResponse> getUserPosts(@PathVariable Long userId,
|
||||
@PageableDefault(size = 20, sort = "createdAt", direction = Sort.Direction.DESC) Pageable pageable) {
|
||||
log.info("get posts of user {}", userId);
|
||||
return postService.getPostsByUser(userId, pageable);
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,13 @@ public class PostResponse {
|
||||
private PostType type;
|
||||
private PostStatus status;
|
||||
private LocalDateTime createdAt;
|
||||
/** Логин автора. */
|
||||
private String userLogin;
|
||||
/**
|
||||
* Тот же логин под старым (ошибочным) именем — для клиентов, которые ещё
|
||||
* читают userEmail. Удалить после перехода фронта на userLogin.
|
||||
*/
|
||||
@Deprecated
|
||||
private String userEmail;
|
||||
private String phone;
|
||||
private List<String> images;
|
||||
|
||||
@@ -19,6 +19,7 @@ public interface PostMapper {
|
||||
Post toEntity(PostRequest request);
|
||||
|
||||
@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
|
||||
|
||||
@@ -12,11 +12,17 @@ import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
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);
|
||||
|
||||
List<Post> findByStatus(PostStatus status);
|
||||
|
||||
List<Post> findByCreatedAtBefore(LocalDateTime date);
|
||||
|
||||
@@ -54,6 +54,7 @@ public class SecurityConfig {
|
||||
.requestMatchers(HttpMethod.GET, "/api/v1/files/**").permitAll()
|
||||
.requestMatchers(HttpMethod.GET, "/api/v1/ads-media/**").permitAll()
|
||||
.requestMatchers(HttpMethod.GET, "/api/v1/posts/**").permitAll()
|
||||
.requestMatchers(HttpMethod.GET, "/api/v1/users/*/posts").permitAll()
|
||||
.requestMatchers(HttpMethod.GET, "/api/v1/reviews/**").permitAll()
|
||||
.requestMatchers("/ws/**").permitAll() // авторизация чата — на уровне STOMP CONNECT interceptor, см. заметку ниже
|
||||
|
||||
@@ -115,6 +116,10 @@ public class SecurityConfig {
|
||||
config.setAllowedOrigins(origins);
|
||||
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
|
||||
config.setAllowedHeaders(List.of("*"));
|
||||
// Без expose браузер прячет эти заголовки от кросс-доменного фронта:
|
||||
// Retry-After нужен для сообщения «повторите через N мин» на 429,
|
||||
// Location — ссылка на созданный ресурс (201 у POST /api/v1/posts)
|
||||
config.setExposedHeaders(List.of("Retry-After", "Location"));
|
||||
config.setAllowCredentials(true);
|
||||
config.setMaxAge(3600L);
|
||||
|
||||
|
||||
@@ -79,15 +79,16 @@ public class PostService {
|
||||
* до транзакции: соединение с БД не держится, пока ждём внешние сервисы.
|
||||
* Если транзакция не прошла, загруженные файлы удаляются.
|
||||
*/
|
||||
public PostRequest create(PostRequest request, List<MultipartFile> images) {
|
||||
public PostResponse create(PostRequest request, List<MultipartFile> images) {
|
||||
User currentUser = userService.getCurrentUser();
|
||||
PostFieldLimits.validate(request.getTitle(), request.getAddress(), request.getPhone(), request.getRewardText());
|
||||
|
||||
AddressInfo location = geocode(request.getLatitude(), request.getLongitude());
|
||||
List<String> imageKeys = uploadImages(images);
|
||||
|
||||
PostResponse created;
|
||||
try {
|
||||
transactionTemplate.executeWithoutResult(status -> {
|
||||
created = transactionTemplate.execute(status -> {
|
||||
Post post = mapper.toEntity(request);
|
||||
post.setCreatedAt(TimeZoneContext.now());
|
||||
post.setStatus(PostStatus.MODERATION);
|
||||
@@ -104,12 +105,14 @@ public class PostService {
|
||||
|
||||
statisticsService.incrementCreated();
|
||||
postCacheService.invalidatePosts();
|
||||
// Ответ собираем в транзакции: картинки и автор — ленивые связи
|
||||
return toResponse(post, true);
|
||||
});
|
||||
} catch (RuntimeException e) {
|
||||
postDeletionService.deleteFilesAfterCommit(imageKeys);
|
||||
throw e;
|
||||
}
|
||||
return request;
|
||||
return created;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -194,6 +197,18 @@ public class PostService {
|
||||
* Владелец видит все свои посты (включая MODERATION и REJECTED), остальные — только
|
||||
* опубликованные (ACTIVE и CLOSED).
|
||||
*/
|
||||
/**
|
||||
* Объявления пользователя постранично (GET /api/v1/users/{userId}/posts).
|
||||
* Владелец видит все свои посты, остальные — только опубликованные.
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public Page<PostResponse> getPostsByUser(Long userId, Pageable pageable) {
|
||||
Page<Post> posts = isCurrentUser(userId)
|
||||
? postRepository.findByUserId(userId, pageable)
|
||||
: postRepository.findByUserIdAndStatusIn(userId, FEED_VISIBLE_STATUSES, pageable);
|
||||
return posts.map(post -> toResponse(post, false));
|
||||
}
|
||||
|
||||
public List<PostResponse> getPostsByUserId(Long userId) {
|
||||
boolean owner = isCurrentUser(userId);
|
||||
|
||||
@@ -317,22 +332,21 @@ public class PostService {
|
||||
return mapper.toResponse(updated);
|
||||
}
|
||||
|
||||
public List<PostResponse> searchByCity(String city) {
|
||||
/**
|
||||
* Устаревший поиск по подстроке города/района — тот же фильтр есть в ленте
|
||||
* (GET /api/v1/posts?city=). Оставлен на переходный период, уже постранично.
|
||||
*/
|
||||
@Deprecated
|
||||
@Transactional(readOnly = true)
|
||||
public Page<PostResponse> searchByCity(String city, Pageable pageable) {
|
||||
if (!StringUtils.hasText(city)) {
|
||||
return List.of();
|
||||
return Page.empty(pageable);
|
||||
}
|
||||
|
||||
Specification<Post> spec = Specification.where(PostSpecification.cityOrDistrictLike(city))
|
||||
.and((root, query, cb) -> root.get("status").in(FEED_VISIBLE_STATUSES));
|
||||
|
||||
List<Post> posts = postRepository.findAll(spec);
|
||||
if (posts.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
return posts.stream()
|
||||
.map(post -> toResponse(post, true))
|
||||
.toList();
|
||||
return postRepository.findAll(spec, pageable).map(post -> toResponse(post, true));
|
||||
}
|
||||
|
||||
public List<String> getCities() {
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.krylov.refound.service;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
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.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 org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageImpl;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
/** GET /api/v1/users/{userId}/posts: что видит владелец и что — все остальные. */
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class PostServiceUserPostsTest {
|
||||
|
||||
@Mock
|
||||
private PostRepository postRepository;
|
||||
@Mock
|
||||
private PostMapper mapper;
|
||||
@Mock
|
||||
private UserService userService;
|
||||
|
||||
@InjectMocks
|
||||
private PostService service;
|
||||
|
||||
private final Pageable pageable = PageRequest.of(0, 20);
|
||||
|
||||
@Test
|
||||
void ownerGetsAllOwnPostsIncludingUnpublished() {
|
||||
User owner = new User();
|
||||
owner.setId(5L);
|
||||
when(userService.getCurrentUser()).thenReturn(owner);
|
||||
Post post = new Post();
|
||||
when(postRepository.findByUserId(5L, pageable)).thenReturn(new PageImpl<>(List.of(post), pageable, 1));
|
||||
PostResponse dto = new PostResponse();
|
||||
when(mapper.toResponse(post)).thenReturn(dto);
|
||||
|
||||
Page<PostResponse> page = service.getPostsByUser(5L, pageable);
|
||||
|
||||
assertThat(page.getContent()).containsExactly(dto);
|
||||
verify(postRepository, never()).findByUserIdAndStatusIn(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void othersGetOnlyPublishedPosts() {
|
||||
User someoneElse = new User();
|
||||
someoneElse.setId(9L);
|
||||
when(userService.getCurrentUser()).thenReturn(someoneElse);
|
||||
when(postRepository.findByUserIdAndStatusIn(eq(5L), eq(PostVisibility.FEED_VISIBLE_STATUSES), eq(pageable)))
|
||||
.thenReturn(Page.empty(pageable));
|
||||
|
||||
Page<PostResponse> page = service.getPostsByUser(5L, pageable);
|
||||
|
||||
assertThat(page.getContent()).isEmpty();
|
||||
verify(postRepository, never()).findByUserId(5L, pageable);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anonymousGetsOnlyPublishedPosts() {
|
||||
when(userService.getCurrentUser())
|
||||
.thenThrow(new ApiException(ErrorCode.UNAUTHORIZED, "Unauthorized", HttpStatus.UNAUTHORIZED));
|
||||
when(postRepository.findByUserIdAndStatusIn(eq(5L), eq(PostVisibility.FEED_VISIBLE_STATUSES), eq(pageable)))
|
||||
.thenReturn(Page.empty(pageable));
|
||||
|
||||
service.getPostsByUser(5L, pageable);
|
||||
|
||||
verify(postRepository, never()).findByUserId(5L, pageable);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user