Skip to content

Commit e1af25c

Browse files
committed
add-friends-likes. Добавить новые методы для лайков и друзей. Добавить хранилища. Добавить сервисы.
1 parent 4efa976 commit e1af25c

File tree

16 files changed

+570
-115
lines changed

16 files changed

+570
-115
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 & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1,74 +1,55 @@
11
package ru.yandex.practicum.filmorate.controller;
22

33
import jakarta.validation.Valid;
4+
import lombok.RequiredArgsConstructor;
45
import lombok.extern.slf4j.Slf4j;
56
import org.springframework.web.bind.annotation.*;
6-
import ru.yandex.practicum.filmorate.exception.ValidationException;
77
import ru.yandex.practicum.filmorate.model.Film;
8+
import ru.yandex.practicum.filmorate.service.FilmService;
89

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

1412
@Slf4j
1513
@RestController
1614
@RequestMapping(value = "/films")
15+
@RequiredArgsConstructor
1716
public class FilmController {
1817

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

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

2725
@PostMapping
2826
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;
27+
return filmService.create(film);
3628
}
3729

3830
@PutMapping
3931
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() + " не найден");
32+
return filmService.update(newFilm);
33+
}
34+
35+
@GetMapping("/{id}")
36+
public Film getFilmById(@PathVariable Long id) {
37+
return filmService.getFilmById(id);
38+
}
39+
40+
@PutMapping("/{id}/like/{userId}")
41+
public void addLike(@PathVariable Long id, @PathVariable Long userId) {
42+
filmService.addLike(id, userId);
5643
}
5744

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

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

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

33
import jakarta.validation.Valid;
4+
import lombok.RequiredArgsConstructor;
45
import lombok.extern.slf4j.Slf4j;
56
import org.springframework.web.bind.annotation.*;
6-
import ru.yandex.practicum.filmorate.exception.ValidationException;
77
import ru.yandex.practicum.filmorate.model.User;
8+
import ru.yandex.practicum.filmorate.service.UserService;
89

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

1412
@Slf4j
1513
@RestController
1614
@RequestMapping(value = "/users")
15+
@RequiredArgsConstructor
1716
public class UserController {
1817

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

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

2725
@PostMapping
2826
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;
27+
return userService.createUser(user);
4028
}
4129

4230
@PutMapping
4331
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());
32+
return userService.updateUser(newUser);
33+
}
5134

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() + " не найден");
35+
@GetMapping("/{id}/friends")
36+
public List<User> getFriends(@PathVariable Long id) {
37+
return userService.getFriendsByUserId(id);
6338
}
6439

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

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-
}
45+
@GetMapping("/{id}/friends/common/{otherId}")
46+
public List<User> getCommonFriends(@PathVariable Long id, @PathVariable Long otherId) {
47+
return userService.getCommonFriends(id, otherId);
8248
}
8349

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-
}
50+
@PutMapping("/{id}/friends/{friendId}")
51+
public void addFriend(@PathVariable Long id, @PathVariable Long friendId) {
52+
userService.addFriend(id, friendId);
9653
}
9754

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