Skip to content

Commit eeb1ecc

Browse files
authored
Merge pull request #15 from vvbakhanovich/add-remove-endpoint
feat: Удаление фильмов и пользователей
2 parents 35a870d + 4766475 commit eeb1ecc

File tree

11 files changed

+82
-5
lines changed

11 files changed

+82
-5
lines changed

pom.xml

+2-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
<parent>
66
<groupId>org.springframework.boot</groupId>
77
<artifactId>spring-boot-starter-parent</artifactId>
8-
<version>2.7.14</version>
8+
<version>2.7.17</version>
99
<relativePath/> <!-- lookup parent from repository -->
1010
</parent>
1111
<groupId>ru.yandex.practicum</groupId>
@@ -54,6 +54,7 @@
5454
<dependency>
5555
<groupId>com.h2database</groupId>
5656
<artifactId>h2</artifactId>
57+
<version>2.2.220</version>
5758
<scope>runtime</scope>
5859
</dependency>
5960

src/main/java/ru/yandex/practicum/filmorate/controller/FilmController.java

+5
Original file line numberDiff line numberDiff line change
@@ -52,5 +52,10 @@ public FilmDto removeLike(@PathVariable long id, @PathVariable long userId) {
5252
public Collection<FilmDto> getMostPopularFilms(@RequestParam(required = false, defaultValue = "10") int count) {
5353
return filmService.getMostPopularFilms(count);
5454
}
55+
56+
@DeleteMapping("/{id}")
57+
public void removeFilm(@PathVariable long id) {
58+
filmService.removeFilm(id);
59+
}
5560
}
5661

src/main/java/ru/yandex/practicum/filmorate/controller/UserController.java

+5
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,11 @@ public void removeFriend(@PathVariable long id, @PathVariable long friendId) {
5959
userService.removeFriend(id, friendId);
6060
}
6161

62+
@DeleteMapping("/{id}")
63+
public void removeUser(@PathVariable long id) {
64+
userService.removeUser(id);
65+
}
66+
6267
@GetMapping("/{id}/recommendations")
6368
public Collection<FilmDto> showRecommendations(@PathVariable long id) {
6469
return userService.showRecommendations(id);

src/main/java/ru/yandex/practicum/filmorate/dao/impl/FilmDbStorage.java

+4-2
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,10 @@ public Film add(final Film film) {
5656
@Override
5757
public void remove(final long id) {
5858
final String sql = "DELETE FROM film WHERE id = ?";
59-
jdbcTemplate.update(sql, id);
59+
int amount = jdbcTemplate.update(sql, id);
60+
if (amount != 1) {
61+
throw new NotFoundException("Фильм с id '" + id + "' не найден.");
62+
}
6063
}
6164

6265
@Override
@@ -69,7 +72,6 @@ public void update(final Film film) {
6972
}
7073

7174
filmGenreStorage.deleteAllById(film.getId());
72-
7375
filmGenreStorage.batchUpdate(film.getId(), film.getGenres());
7476
}
7577

src/main/java/ru/yandex/practicum/filmorate/service/FilmService.java

+2
Original file line numberDiff line numberDiff line change
@@ -17,5 +17,7 @@ public interface FilmService {
1717

1818
FilmDto removeLike(long filmId, long userId);
1919

20+
void removeFilm(long filmId);
21+
2022
Collection<FilmDto> getMostPopularFilms(final int count);
2123
}

src/main/java/ru/yandex/practicum/filmorate/service/UserService.java

+2
Original file line numberDiff line numberDiff line change
@@ -23,5 +23,7 @@ public interface UserService {
2323

2424
void removeFriend(long userId, long friendId);
2525

26+
void removeUser(long userId);
27+
2628
Collection<FilmDto> showRecommendations(long id);
2729
}

src/main/java/ru/yandex/practicum/filmorate/service/impl/FilmServiceImpl.java

+10
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,16 @@ public FilmDto removeLike(final long filmId, final long userId) {
114114
return toDto(filmStorage.findById(filmId));
115115
}
116116

117+
/**
118+
* Удаление фильма.
119+
*
120+
* @param filmId идентификатор фильма, который будет удален
121+
*/
122+
@Override
123+
public void removeFilm(long filmId) {
124+
filmStorage.remove(filmId);
125+
}
126+
117127
/**
118128
* Получение списка самых популярных фильмов. Под популярностью понимается количество лайков у фильма. Чем больше
119129
* лайков, тем популярнее фильм.

src/main/java/ru/yandex/practicum/filmorate/service/impl/UserServiceImpl.java

+10
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,16 @@ public void removeFriend(final long userId, final long friendId) {
156156
log.info("Пользователи с id {} и {} перестали быть друзьями", userId, friendId);
157157
}
158158

159+
/**
160+
* Удаление пользователя.
161+
*
162+
* @param userId идентификатор пользователя, который будет удален
163+
*/
164+
@Override
165+
public void removeUser(long userId) {
166+
userStorage.remove(userId);
167+
}
168+
159169
/**
160170
* Создание рекомендаций пользователю фильмов, которые ему могут понравиться. Для подготовки рекомендаций
161171
* выгружаем данные из таблицы film_like, находим пользователей с максимальным количеством одинаковых с нашим

src/main/resources/schema.sql

+2-2
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ CREATE TABLE IF NOT EXISTS FILM_GENRE(
2525
ID INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 1) NOT NULL PRIMARY KEY,
2626
FILM_ID INTEGER NOT NULL,
2727
GENRE_ID INTEGER NOT NULL,
28-
FOREIGN KEY (FILM_ID) REFERENCES FILM(ID),
28+
FOREIGN KEY (FILM_ID) REFERENCES FILM(ID) ON DELETE CASCADE,
2929
FOREIGN KEY (GENRE_ID) REFERENCES GENRE(ID)
3030
);
3131

@@ -59,7 +59,7 @@ CREATE TABLE IF NOT EXISTS FILM_LIKE(
5959
FILM_ID INTEGER NOT NULL,
6060
USER_ID INTEGER NOT NULL,
6161
CONSTRAINT pk_film_like PRIMARY KEY (FILM_ID, USER_ID),
62-
FOREIGN KEY (FILM_ID) REFERENCES FILM(ID),
62+
FOREIGN KEY (FILM_ID) REFERENCES FILM(ID) ON DELETE CASCADE,
6363
FOREIGN KEY (USER_ID) REFERENCES FILMORATE_USER(ID)
6464
);
6565

src/test/java/ru/yandex/practicum/filmorate/storage/FilmDbStorageTest.java

+20
Original file line numberDiff line numberDiff line change
@@ -287,6 +287,26 @@ void testFindByIdWithAllFields() {
287287
.isEqualTo(film);
288288
}
289289

290+
@Test
291+
@DisplayName("Тест удаление фильма")
292+
void testDeleteFilm() {
293+
Film newFilm = filmDbStorage.add(film);
294+
filmDbStorage.remove(newFilm.getId());
295+
296+
String formattedResponse = String.format("Фильм с id '%s' не найден.", newFilm.getId());
297+
NotFoundException e = assertThrows(NotFoundException.class, () -> filmDbStorage.findById(newFilm.getId()));
298+
assertEquals(formattedResponse, e.getMessage());
299+
}
300+
301+
@Test
302+
@DisplayName("Тест удаление несуществующего фильма")
303+
void testDeleteNotExistingUser() {
304+
int filmId = 999;
305+
String formattedResponse = String.format("Фильм с id '%s' не найден.", filmId);
306+
NotFoundException e = assertThrows(NotFoundException.class, () -> filmDbStorage.remove(filmId));
307+
assertEquals(formattedResponse, e.getMessage());
308+
}
309+
290310
@Test
291311
@DisplayName("Тест на получение самых популярных фильмов с несколькими жанрами")
292312
void testMostPopularFilmsWithSeveralGenres() {

src/test/java/ru/yandex/practicum/filmorate/storage/UserDbStorageTest.java

+20
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,26 @@ void testGetEmptyFriendsList() {
345345
.isEmpty();
346346
}
347347

348+
@Test
349+
@DisplayName("Тест удаление пользователя")
350+
void testDeleteUser() {
351+
User newUser = userStorage.add(user);
352+
userStorage.remove(newUser.getId());
353+
354+
String formattedResponse = String.format("Пользователь с id '%s' не найден.", newUser.getId());
355+
NotFoundException e = assertThrows(NotFoundException.class, () -> userStorage.findById(newUser.getId()));
356+
assertEquals(formattedResponse, e.getMessage());
357+
}
358+
359+
@Test
360+
@DisplayName("Тест удаление несуществующего пользователя")
361+
void testDeleteNotExistingUser() {
362+
int userId = 999;
363+
String formattedResponse = String.format("Пользователь с id '%s' не найден.", userId);
364+
NotFoundException e = assertThrows(NotFoundException.class, () -> userStorage.remove(userId));
365+
assertEquals(formattedResponse, e.getMessage());
366+
}
367+
348368
@Test
349369
@DisplayName("Тест получения мапы с ключами userId и сетом с списком айдишников залайканных фильмов.")
350370
void testGetRecommendationsList() {

0 commit comments

Comments
 (0)