Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,11 @@
<artifactId>gson</artifactId>
<version>2.8.9</version>
</dependency>
<dependency>
<groupId>org.zalando</groupId>
<artifactId>logbook-spring-boot-starter</artifactId>
<version>3.7.2</version>
</dependency>
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@

import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import ru.yandex.practicum.filmorate.model.Film;
import ru.yandex.practicum.filmorate.response.SuccessResponse;
import ru.yandex.practicum.filmorate.service.FilmService;

import java.util.Collection;
Expand All @@ -17,16 +19,39 @@ public class FilmController {

@GetMapping
public Collection<Film> getFilms() {
return filmService.getFilms();
return filmService.getAllFilms();
}

@GetMapping("/{filmId}")
public Film getFilm(@PathVariable Long filmId) {
return filmService.getFilmById(filmId);
}

@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Film addFilm(@Valid @RequestBody Film film) {
return filmService.addFilm(film);
return filmService.createFilm(film);
}

@PutMapping
public Film updateFilm(@Valid @RequestBody Film newFilm) {
return filmService.updateFilm(newFilm);
}

@PutMapping("/{id}/like/{userId}")
public SuccessResponse likeFilm(@PathVariable Long id, @PathVariable Long userId) {
filmService.likeFilm(id, userId);
return new SuccessResponse();
}

@DeleteMapping("/{id}/like/{userId}")
public SuccessResponse removeLikeFilm(@PathVariable Long id, @PathVariable Long userId) {
filmService.removeLikeFilm(id, userId);
return new SuccessResponse();
}

@GetMapping("/popular")
public Collection<Film> getPopularFilms(@RequestParam(defaultValue = "10") int count) {
return filmService.getPopularFilms(count);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@

import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import ru.yandex.practicum.filmorate.model.User;
import ru.yandex.practicum.filmorate.response.SuccessResponse;
import ru.yandex.practicum.filmorate.service.UserService;

import java.util.Collection;
Expand All @@ -17,16 +19,48 @@ public class UserController {

@GetMapping
public Collection<User> getUsers() {
return userService.getUsers();
return userService.getAllUsers();
}

@GetMapping("/{userId}")
public User getFilm(@PathVariable Long userId) {
return userService.getUserById(userId);
}

@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public User createUser(@Valid @RequestBody User user) {
return userService.addUser(user);
return userService.createUser(user);
}

@PutMapping
public User updateUser(@Valid @RequestBody User newUser) {
return userService.updateUser(newUser);
}

@PutMapping("/{id}/friends/{friendId}")
public SuccessResponse addFriend(@PathVariable Long id, @PathVariable Long friendId) {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В целом, в контроллерах такого вида можно ничего не возвращать – void
отсутствие исключений может быть равно успешному вызову

userService.addFriend(id, friendId);
return new SuccessResponse();
}

@DeleteMapping("/{id}/friends/{friendId}")
public SuccessResponse removeFriend(@PathVariable Long id, @PathVariable Long friendId) {
userService.removeFriend(id, friendId);
return new SuccessResponse();
}

@GetMapping("/{id}/friends")
public Collection<User> getFriends(@PathVariable Long id) {
return userService.getUserFriends(id);
}

@GetMapping("/{id}/friends/common/{otherId}")
public Collection<User> getCommonFriends(@PathVariable Long id, @PathVariable Long otherId) {
return userService.getCommonUserFriends(id, otherId);
}




}
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
package ru.yandex.practicum.filmorate.exception;

import lombok.Getter;


@Getter
public class NotFoundException extends RuntimeException {
public String name = "not found";

public NotFoundException(String message) {
super(message);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package ru.yandex.practicum.filmorate.exception;

import lombok.Getter;

@Getter
public class OtherException extends RuntimeException {
String name = "server error";

public OtherException(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
package ru.yandex.practicum.filmorate.exception;

import lombok.Getter;

@Getter
public class ValidationException extends RuntimeException {
String name = "validation error";

public ValidationException(String message) {
super(message);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package ru.yandex.practicum.filmorate.handler;


import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import ru.yandex.practicum.filmorate.exception.NotFoundException;
import ru.yandex.practicum.filmorate.exception.OtherException;
import ru.yandex.practicum.filmorate.exception.ValidationException;
import ru.yandex.practicum.filmorate.response.ErrorResponse;

import java.util.List;

@Slf4j
@RestControllerAdvice
public class ErrorHandler {

@ExceptionHandler
@ResponseStatus(HttpStatus.NOT_FOUND)
public ErrorResponse handleNotFound(final NotFoundException e) {
return new ErrorResponse(e.getName(), e.getMessage());
}

@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse handleValidationException(MethodArgumentNotValidException ex) {
List<String> errors = ex.getBindingResult().getFieldErrors().stream()
.map(FieldError::getDefaultMessage)
.toList();
String message = String.join("\n", errors);
log.warn("Ошибка валидации: {}", errors);

return new ErrorResponse("validation error", message);
}

@ExceptionHandler
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse handleValidationError(final ValidationException e) {
return new ErrorResponse(e.getName(), e.getMessage());
}

@ExceptionHandler
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ErrorResponse handleInternalServerError(final OtherException e) {
return new ErrorResponse(e.getName(), e.getMessage());
}

}

This file was deleted.

15 changes: 13 additions & 2 deletions src/main/java/ru/yandex/practicum/filmorate/model/Film.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,22 @@

import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.validation.constraints.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDate;
import java.util.HashSet;
import java.util.Set;

/**
* Film.
*/

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Film {
private Long id;
private Set<Long> usersLikes = new HashSet<>();

@NotBlank(message = "Название фильма не может быть пустым")
private String name;
Expand All @@ -27,6 +30,14 @@ public class Film {
@Positive(message = "Продолжительность фильма должна быть положительным числом")
private Integer duration;

public Film(Long id, String name, String description, LocalDate releaseDate, Integer duration) {
this.id = id;
this.name = name;
this.description = description;
this.releaseDate = releaseDate;
this.duration = duration;
}

@AssertTrue(message = "Дата релиза фильма должна быть не раньше 28 декабря 1895 года")
@JsonIgnore
public boolean isReleaseDateValid() {
Expand Down
15 changes: 13 additions & 2 deletions src/main/java/ru/yandex/practicum/filmorate/model/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,22 @@
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.PastOrPresent;
import jakarta.validation.constraints.Pattern;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDate;
import java.util.HashSet;
import java.util.Set;

/**
* User.
*/

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Long id;
private Set<Long> friends = new HashSet<>();

@Email(message = "Электронная почта пользователя должна соответствовать формату электронного адреса")
@NotBlank(message = "Электронная почта пользователя не может быть пустой")
Expand All @@ -29,4 +32,12 @@ public class User {

@PastOrPresent(message = "Дата рождения пользователя не может быть в будущем")
private LocalDate birthday;

public User(Long id, String email, String login, String name, LocalDate birthday) {
this.id = id;
this.email = email;
this.login = login;
this.name = name;
this.birthday = birthday;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package ru.yandex.practicum.filmorate.response;


import lombok.Data;
import lombok.RequiredArgsConstructor;

@Data
@RequiredArgsConstructor
public class ErrorResponse {
private final String error;
private final String message;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package ru.yandex.practicum.filmorate.response;

import lombok.Data;
import lombok.RequiredArgsConstructor;

@Data
@RequiredArgsConstructor
public class SuccessResponse {
private final String status = "success";
}
Loading
Loading