Skip to content

Commit 7c971db

Browse files
authored
Merge pull request #2 from walder86/add-friends-likes
add-friends-likes. Добавить новые методы для лайков и друзей.
2 parents 4efa976 + a5ce0bb commit 7c971db

File tree

16 files changed

+560
-119
lines changed

16 files changed

+560
-119
lines changed

pom.xml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,11 @@
3636
<groupId>org.springframework.boot</groupId>
3737
<artifactId>spring-boot-starter-validation</artifactId>
3838
</dependency>
39+
<dependency>
40+
<groupId>org.zalando</groupId>
41+
<artifactId>logbook-spring-boot-starter</artifactId>
42+
<version>3.7.2</version>
43+
</dependency>
3944
</dependencies>
4045

4146
<build>
Lines changed: 25 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -1,74 +1,53 @@
11
package ru.yandex.practicum.filmorate.controller;
22

33
import jakarta.validation.Valid;
4-
import lombok.extern.slf4j.Slf4j;
4+
import lombok.RequiredArgsConstructor;
55
import org.springframework.web.bind.annotation.*;
6-
import ru.yandex.practicum.filmorate.exception.ValidationException;
76
import ru.yandex.practicum.filmorate.model.Film;
7+
import ru.yandex.practicum.filmorate.service.FilmService;
88

9-
import java.time.LocalDate;
10-
import java.util.Collection;
11-
import java.util.HashMap;
12-
import java.util.Map;
9+
import java.util.List;
1310

14-
@Slf4j
1511
@RestController
1612
@RequestMapping(value = "/films")
13+
@RequiredArgsConstructor
1714
public class FilmController {
1815

19-
private final Map<Long, Film> films = new HashMap<>();
16+
final FilmService filmService;
2017

2118
@GetMapping
22-
public Collection<Film> findAll() {
23-
log.info("Запрос всех фильмов");
24-
return films.values();
19+
public List<Film> findAll() {
20+
return filmService.getFilms();
2521
}
2622

2723
@PostMapping
2824
public Film create(@Valid @RequestBody Film film) {
29-
checkDate(film);
30-
31-
film.setId(getNextId());
32-
33-
films.put(film.getId(), film);
34-
log.info("Фильм добавлен");
35-
return film;
25+
return filmService.create(film);
3626
}
3727

3828
@PutMapping
3929
public Film update(@Valid @RequestBody Film newFilm) {
40-
if (newFilm.getId() == null) {
41-
log.debug("Не указан Id при обновлении фильма");
42-
throw new ValidationException("Не указан Id при обновлении фильма");
43-
}
44-
checkDate(newFilm);
45-
if (films.containsKey(newFilm.getId())) {
46-
Film oldFilm = films.get(newFilm.getId());
47-
oldFilm.setName(newFilm.getName());
48-
oldFilm.setDescription(newFilm.getDescription());
49-
oldFilm.setReleaseDate(newFilm.getReleaseDate());
50-
oldFilm.setDuration(newFilm.getDuration());
51-
log.info("Фильм с id " + newFilm.getId() + " обновлен");
52-
return oldFilm;
53-
}
54-
log.debug("Фильм с id = " + newFilm.getId() + " не найден");
55-
throw new ValidationException("Фильм с id = " + newFilm.getId() + " не найден");
30+
return filmService.update(newFilm);
31+
}
32+
33+
@GetMapping("/{id}")
34+
public Film getFilmById(@PathVariable Long id) {
35+
return filmService.getFilmById(id);
36+
}
37+
38+
@PutMapping("/{id}/like/{userId}")
39+
public void addLike(@PathVariable Long id, @PathVariable Long userId) {
40+
filmService.addLike(id, userId);
5641
}
5742

58-
private long getNextId() {
59-
long currentMaxId = films.keySet()
60-
.stream()
61-
.mapToLong(id -> id)
62-
.max()
63-
.orElse(0);
64-
return ++currentMaxId;
43+
@DeleteMapping("/{id}/like/{userId}")
44+
public void removeLike(@PathVariable Long id, @PathVariable Long userId) {
45+
filmService.removeLike(id, userId);
6546
}
6647

67-
private void checkDate(Film film) {
68-
if (film.getReleaseDate().isBefore(LocalDate.of(1895, 12, 28))) {
69-
log.debug("Дата рождения не может быть в будущем");
70-
throw new ValidationException("Дата рождения не может быть в будущем");
71-
}
48+
@GetMapping("/popular")
49+
public List<Film> getPopularFilms(@RequestParam(required = false, defaultValue = "10") Long count) {
50+
return filmService.getPopularFilms(count);
7251
}
7352

7453
}
Lines changed: 27 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -1,104 +1,59 @@
11
package ru.yandex.practicum.filmorate.controller;
22

33
import jakarta.validation.Valid;
4-
import lombok.extern.slf4j.Slf4j;
4+
import lombok.RequiredArgsConstructor;
55
import org.springframework.web.bind.annotation.*;
6-
import ru.yandex.practicum.filmorate.exception.ValidationException;
76
import ru.yandex.practicum.filmorate.model.User;
7+
import ru.yandex.practicum.filmorate.service.UserService;
88

9-
import java.time.LocalDate;
10-
import java.util.Collection;
11-
import java.util.HashMap;
12-
import java.util.Map;
9+
import java.util.List;
1310

14-
@Slf4j
1511
@RestController
1612
@RequestMapping(value = "/users")
13+
@RequiredArgsConstructor
1714
public class UserController {
1815

19-
private final Map<Long, User> users = new HashMap<>();
16+
final UserService userService;
2017

2118
@GetMapping
22-
public Collection<User> findAll() {
23-
log.info("Запрос всех пользователей");
24-
return users.values();
19+
public List<User> findAll() {
20+
return userService.getUsers();
2521
}
2622

2723
@PostMapping
2824
public User create(@Valid @RequestBody User user) {
29-
30-
checkEmail(user.getEmail());
31-
checkLogin(user.getLogin());
32-
checkBirthday(user.getBirthday());
33-
34-
user.setId(getNextId());
35-
user.setNameWithCheck(user);
36-
37-
users.put(user.getId(), user);
38-
log.info("Пользователь добавлен");
39-
return user;
25+
return userService.createUser(user);
4026
}
4127

4228
@PutMapping
4329
public User update(@Valid @RequestBody User newUser) {
44-
if (newUser.getId() == null) {
45-
log.debug("Не указан Id при обновлении пользователя");
46-
throw new ValidationException("Не указан Id при обновлении пользователя");
47-
}
48-
checkEmail(newUser.getEmail());
49-
checkLogin(newUser.getLogin());
50-
checkBirthday(newUser.getBirthday());
30+
return userService.updateUser(newUser);
31+
}
5132

52-
if (users.containsKey(newUser.getId())) {
53-
User oldUser = users.get(newUser.getId());
54-
oldUser.setEmail(newUser.getEmail());
55-
oldUser.setNameWithCheck(newUser);
56-
oldUser.setLogin(newUser.getLogin());
57-
oldUser.setBirthday(newUser.getBirthday());
58-
log.info("Пользователь с id " + newUser.getId() + " обновлен");
59-
return oldUser;
60-
}
61-
log.debug("Пользователь с id = " + newUser.getId() + " не найден");
62-
throw new ValidationException("Пользователь с id = " + newUser.getId() + " не найден");
33+
@GetMapping("/{id}/friends")
34+
public List<User> getFriends(@PathVariable Long id) {
35+
return userService.getFriendsByUserId(id);
6336
}
6437

65-
private long getNextId() {
66-
long currentMaxId = users.keySet()
67-
.stream()
68-
.mapToLong(id -> id)
69-
.max()
70-
.orElse(0);
71-
return ++currentMaxId;
38+
@GetMapping("/{id}")
39+
public User getUserById(@PathVariable Long id) {
40+
return userService.getUserById(id);
7241
}
7342

74-
private void checkEmail(String email) {
75-
boolean existEmail = users.values().stream()
76-
.map(User::getEmail)
77-
.anyMatch(email::equals);
78-
if (existEmail) {
79-
log.debug("Пользователь с почтой " + email + " уже существует");
80-
throw new ValidationException("Пользователь с почтой " + email + " уже существует");
81-
}
43+
@GetMapping("/{id}/friends/common/{otherId}")
44+
public List<User> getCommonFriends(@PathVariable Long id, @PathVariable Long otherId) {
45+
return userService.getCommonFriends(id, otherId);
8246
}
8347

84-
private void checkLogin(String login) {
85-
if (login.contains(" ")) {
86-
log.debug("Логин должен быть без пробелов");
87-
throw new ValidationException("Логин должен быть без пробелов");
88-
}
89-
boolean existEmail = users.values().stream()
90-
.map(User::getLogin)
91-
.anyMatch(login::equals);
92-
if (existEmail) {
93-
log.debug("Пользователь с логином " + login + " уже существует");
94-
throw new ValidationException("Пользователь с логином " + login + " уже существует");
95-
}
48+
@PutMapping("/{id}/friends/{friendId}")
49+
public void addFriend(@PathVariable Long id, @PathVariable Long friendId) {
50+
userService.addFriend(id, friendId);
9651
}
9752

98-
private void checkBirthday(LocalDate birthday) {
99-
if (birthday.isAfter(LocalDate.now())) {
100-
log.debug("Дата рождения не может быть в будущем");
101-
throw new ValidationException("Дата рождения не может быть в будущем");
102-
}
53+
@DeleteMapping("/{id}/friends/{friendId}")
54+
public void removeFriend(@PathVariable Long id, @PathVariable Long friendId) {
55+
userService.removeFriends(id, friendId);
10356
}
57+
58+
10459
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package ru.yandex.practicum.filmorate.exception;
2+
3+
public class AlreadyExistsException extends RuntimeException {
4+
public AlreadyExistsException(String message) {
5+
super(message);
6+
}
7+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package ru.yandex.practicum.filmorate.exception;
2+
3+
import lombok.Data;
4+
5+
@Data
6+
class ErrorResponse {
7+
private final String error;
8+
private final String description;
9+
10+
public ErrorResponse(String error, String description) {
11+
this.error = error;
12+
this.description = description;
13+
}
14+
15+
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package ru.yandex.practicum.filmorate.exception;
2+
3+
import org.springframework.http.HttpStatus;
4+
import org.springframework.web.bind.annotation.ResponseStatus;
5+
import org.springframework.web.bind.annotation.RestControllerAdvice;
6+
7+
@RestControllerAdvice
8+
public class ExceptionHandler {
9+
10+
11+
@org.springframework.web.bind.annotation.ExceptionHandler
12+
@ResponseStatus(HttpStatus.BAD_REQUEST)
13+
public ErrorResponse validateHandler(ValidationException e) {
14+
return new ErrorResponse(
15+
"Ошибка валидации",
16+
e.getMessage()
17+
);
18+
}
19+
20+
@org.springframework.web.bind.annotation.ExceptionHandler
21+
@ResponseStatus(HttpStatus.NOT_FOUND)
22+
public ErrorResponse notFoundHandler(NotFoundException e) {
23+
return new ErrorResponse(
24+
"Объект не найден",
25+
e.getMessage()
26+
);
27+
}
28+
29+
@org.springframework.web.bind.annotation.ExceptionHandler
30+
@ResponseStatus(HttpStatus.BAD_REQUEST)
31+
public ErrorResponse alreadyExistHandler(AlreadyExistsException e) {
32+
return new ErrorResponse(
33+
"Объект уже существует",
34+
e.getMessage()
35+
);
36+
}
37+
38+
@org.springframework.web.bind.annotation.ExceptionHandler
39+
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
40+
public ErrorResponse exceptionHandler(RuntimeException e) {
41+
return new ErrorResponse(
42+
"Внутренняя ошибка сервера",
43+
e.getMessage()
44+
);
45+
}
46+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package ru.yandex.practicum.filmorate.exception;
2+
3+
public class NotFoundException extends RuntimeException {
4+
public NotFoundException(String message) {
5+
super(message);
6+
}
7+
}

src/main/java/ru/yandex/practicum/filmorate/model/Film.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
import lombok.NoArgsConstructor;
1111

1212
import java.time.LocalDate;
13+
import java.util.ArrayList;
14+
import java.util.List;
1315

1416
@Data
1517
@Builder(toBuilder = true)
@@ -32,4 +34,14 @@ public class Film {
3234
@Positive
3335
@NotNull
3436
private Integer duration;
37+
38+
private List<Long> likes = new ArrayList<>();
39+
40+
public void addLike(Long userId) {
41+
likes.add(userId);
42+
}
43+
44+
public void removeLike(Long userId) {
45+
likes.remove(userId);
46+
}
3547
}

src/main/java/ru/yandex/practicum/filmorate/model/User.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
import lombok.NoArgsConstructor;
1010

1111
import java.time.LocalDate;
12+
import java.util.ArrayList;
13+
import java.util.List;
1214

1315
@Data
1416
@Builder(toBuilder = true)
@@ -30,6 +32,16 @@ public class User {
3032
@NotNull
3133
private LocalDate birthday;
3234

35+
private List<Long> friends = new ArrayList<>();
36+
37+
public void addFriend(Long friendId) {
38+
friends.add(friendId);
39+
}
40+
41+
public void removeFriend(Long friendId) {
42+
friends.remove(friendId);
43+
}
44+
3345
public void setNameWithCheck(User user) {
3446
if (user.getName() == null || user.getName().isBlank())
3547
this.setName(user.getLogin());

0 commit comments

Comments
 (0)