22
33import jakarta .validation .Valid ;
44
5- import jakarta .validation .ValidationException ;
5+ import jakarta .validation .constraints . Positive ;
66import org .slf4j .Logger ;
77import org .slf4j .LoggerFactory ;
8+ import org .springframework .beans .factory .annotation .Autowired ;
89import org .springframework .http .HttpStatus ;
9- import org .springframework .http .ResponseEntity ;
10-
10+ import org .springframework .validation .annotation .Validated ;
1111import org .springframework .web .bind .annotation .*;
1212import ru .yandex .practicum .filmorate .model .User ;
13+ import ru .yandex .practicum .filmorate .service .UserService ;
1314
1415import java .util .Collection ;
15- import java .util .HashMap ;
16- import java .util .Map ;
1716
17+ @ Validated
1818@ RestController
1919@ RequestMapping ("/users" )
2020public class UserController {
2121
22- private final ValidateController validate = new ValidateController ();
23- private final Map <Long , User > users = new HashMap <>();
22+ private final UserService userService ;
23+
24+ private final Logger logger = LoggerFactory .getLogger (UserController .class );
25+
26+ @ Autowired
27+ public UserController (UserService userService ) {
28+ this .userService = userService ;
29+ }
2430
25- private final Logger log = LoggerFactory .getLogger (UserController .class );
31+ @ GetMapping ("/{id}" )
32+ @ ResponseStatus (HttpStatus .OK )
33+ public User getUserId (@ Positive (message = "неверное значение" ) @ PathVariable long id ) {
34+ logger .info ("вывод пользователя по ID" );
35+ return userService .getUserId (id );
36+ }
2637
27- @ GetMapping //запрос всех пользователей
28- public ResponseEntity <Collection <User >> usersAll () {
38+ @ GetMapping
39+ @ ResponseStatus (HttpStatus .OK )
40+ public Collection <User > userAll () {
41+ logger .info ("вывод списка пользователей" );
42+ return userService .getAll ();
43+ }
2944
30- log .info ("вывод списка пользователей" );
31- return ResponseEntity .ok (users .values ());
45+ @ PostMapping
46+ @ ResponseStatus (HttpStatus .CREATED )
47+ public User create (@ Valid @ RequestBody User user ) {
48+ logger .info ("Пользователь добавлен" );
49+ return userService .create (user );
3250 }
3351
34- @ PostMapping //добавление нового пользователя
35- public ResponseEntity <?> create (@ Valid @ RequestBody User user ) {
36- validate .validateUser (user );
37-
38- if (users .containsValue (user )) {
39- log .warn ("ошибка добавления пользователя, такой пользователь уже есть" );
40- return ResponseEntity .status (HttpStatus .BAD_REQUEST ).body ("ошибка добавления пользователя, такой пользователь уже есть" );
41- }
42- user .setId (getNextId ());
43- users .put (user .getId (), user );
44- log .info ("пользователь создан id: " + user .getId ());
45- return ResponseEntity .status (HttpStatus .CREATED ).body (user ); //отрпавляем ответ с статусом и телом
52+ @ DeleteMapping ("/{id}" )
53+ @ ResponseStatus (HttpStatus .OK )
54+ public void delete (@ Positive (message = "неверное значение" ) @ PathVariable long id ) {
55+ logger .info ("Удаление id=" + id );
56+ userService .delete (id );
4657 }
4758
48- @ PutMapping //обновление пользователя
49- public ResponseEntity <?> update (@ Valid @ RequestBody User newUser ) {
50- if (newUser .getId () == null ) {
51- log .warn ("ID пустой" );
52- throw new ValidationException (" ID пустой" );
53- // изначально сделал чтоб в теле была ошибка, но не прошло тесты в Postman
54- // return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("ID пустой");
55- }
56- if (!users .containsKey (newUser .getId ())) {
57- log .warn ("пользователь с таким ID не найден" );
58- throw new ValidationException ("пользователь с таким ID не найден" );
59- // изначально сделал чтоб в теле была ошибка, но не прошло тесты в Postman
60- // return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("пользователь с таким ID не найден");
61- }
62- validate .validateUser (newUser );
63- User oldUser = users .get (newUser .getId ());
64- oldUser .setEmail (newUser .getEmail ());
65- oldUser .setLogin (newUser .getLogin ());
66- oldUser .setBirthday (newUser .getBirthday ());
67- oldUser .setName (newUser .getName ());
68- log .info ("пользователь изменен" );
69- return ResponseEntity .ok (oldUser );
59+ @ PutMapping
60+ @ ResponseStatus (HttpStatus .OK )
61+ public User update (@ RequestBody User newUser ) {
62+ logger .info ("запись пользователя обновлена" );
63+ return userService .update (newUser );
7064 }
7165
72- private long getNextId () {
73- long currentMaxId = users .keySet ()
74- .stream ()
75- .mapToLong (id -> id )
76- .max ()
77- .orElse (0 );
78- return ++currentMaxId ;
66+ @ PutMapping ("/{id}/friends/{friendsId}" )
67+ @ ResponseStatus (HttpStatus .OK )
68+ public Collection <Long > friendsAdd (@ Positive (message = "неверное значение" ) @ PathVariable long id ,
69+ @ Positive (message = "неверное значение" ) @ PathVariable long friendsId ) {
70+ logger .info ("добавили в друзья" );
71+ return userService .friendsAdd (id , friendsId );
72+ }
73+
74+ @ DeleteMapping ("/{id}/friends/{friendsId}" )
75+ @ ResponseStatus (HttpStatus .OK )
76+ public Collection <Long > friendsDelete (@ Positive (message = "неверное значение" ) @ PathVariable long id ,
77+ @ Positive (message = "неверное значение" ) @ PathVariable long friendsId ) {
78+ logger .info ("удалили из друзей" );
79+ return userService .friendsDelete (id , friendsId );
80+ }
81+
82+ @ GetMapping ("/{id}/friends" )
83+ @ ResponseStatus (HttpStatus .OK )
84+ public Collection <User > friendsGetList (@ Positive (message = "неверное значение" ) @ PathVariable long id ) {
85+ logger .info ("показывает список друзей" );
86+ return userService .friendsGetList (id );
87+ }
7988
89+ @ GetMapping ("/{id}/friends/common/{otherId}" )
90+ @ ResponseStatus (HttpStatus .OK )
91+ public Collection <User > friendsGetCommonList (@ Positive (message = "неверное значение" ) @ PathVariable long id ,
92+ @ Positive (message = "неверное значение" ) @ PathVariable long otherId ) {
93+ logger .info ("показывает список друзей" );
94+ return userService .friendsGetCommonList (id , otherId );
8095 }
81- }
96+ }
0 commit comments