generated from yandex-praktikum/java-filmorate
-
Notifications
You must be signed in to change notification settings - Fork 0
add database #4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
progingir
wants to merge
118
commits into
main
Choose a base branch
from
add-database
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
add database #4
Changes from all commits
Commits
Show all changes
118 commits
Select commit
Hold shift + click to select a range
da5d1a2
первая попытка
progingir 752106b
удален файл
progingir 61ca261
стиль
progingir 70c62e7
обновлены запросы
progingir 566820a
поменяла запросы
progingir b94fb11
изменен контроллер
progingir af1a962
куча изменений
progingir 883df51
опять стиль
progingir a1292fb
пофиксила ошибочки
progingir b6d1eb9
3 утра
progingir f9f1c77
поправила класс фильмов
progingir a467709
14
progingir d80198c
2
progingir cb61ead
работаем с жанрами
progingir 620288c
работаем с мпа
progingir 6b1bc34
добавила обработку еще одной ошибки
progingir 9fc8e20
попытка обработать ошибки
progingir cc7151a
проверка фильмов
progingir 6dbf4f5
стиль стиль
progingir c8b6ad5
aaaa
progingir 685fb63
все изменения назад
progingir c63d6fe
добавила обработчик
progingir fa2d755
aaaaaaaaaaaaaaaaaa
progingir c85e045
132 попытка
progingir 943350e
откат изменений
progingir bf5baf9
валидация
progingir 4725a47
обновила методы update create
progingir 546be13
исправила исключение
progingir 801d655
рефракторинг класса filmdbstorage
progingir 9977efd
еще рефракторинг
progingir d01fd5d
рефракторингг
progingir 84cbfe8
все еще делаем код красивым
progingir 0863670
побаловалась с документацией
progingir 264bb8f
убраны выбросы исключений
progingir 34fb7e6
стиль
progingir 8587e4d
убрала лишний парсинг
progingir 61fcc05
убрала mpa constant
progingir a99c72b
notfoundexception и название запросов
progingir 8c6a131
вынесла классы
progingir 9407269
стиль
progingir e35156a
убрала assert
progingir 9641c76
убрала множественные селекторы
progingir 2e335dd
поправила конф
progingir cdd107d
стиль
progingir 8e2ef28
все изменения назад, потому что падают с ошибкой
progingir 1e3f047
все изменения назад
progingir 57c2362
убрала лишнюю проверку
progingir 11b239e
изменения назад, потому что опять ошибка
progingir c9d1736
добавила foreign key
progingir 084da27
еще один foreign key
progingir bcad0ce
откат по тестам
progingir d2fa888
переделываю через json
progingir 5b6aaec
стиль
progingir ffc8e2b
откат изменений
progingir 4da9d03
убрала парсер
progingir 3d7acc3
откат изменений
progingir fe91557
убрала throws
progingir 50bdf27
стиль
progingir a3cc1c0
добавлены модификаторы доступа
progingir 28a9df4
переименовала
progingir 1ffdbfc
убрала ненужные методы
progingir e920739
получаем общих друзей через inner join
progingir e8ca87a
откат изменений
progingir de3ef48
defaultValue = 10 так же оставила
progingir 096d0c7
поменяла сообщения об ошибках
progingir c034739
передаю параметр count в запрос
progingir cd8b0d7
откат правок
progingir 1f37ed4
убрала лишнюю аннотацию
progingir 6a6b99a
стиль
progingir 2ce3532
переименовала запросы
progingir 6ac5615
стиль
progingir 4d7f8bd
стиииль
progingir 8efda50
вынесла классы
progingir c450028
спасите
progingir 2936d2f
ненужные импорты
progingir acbdf27
убрала нереализованный метод
progingir 07f40cd
поменяла аннотацию
progingir a61057c
ненужный import
progingir dd74d6f
пора бы настроить идею на удаление ненужных импортов, да?
progingir d37c609
без аннотаций вообще все падает, вернула обратно
progingir c7d8b6b
получение друзей через один запрос
progingir 051172f
название переменной
progingir 3095016
пробуем
progingir 1b2cbfa
убрала проверку
progingir efa09ab
возврат изменений
progingir a2f9c7b
пробуем
progingir 4ab5358
кошмар
progingir 9c5a915
откат изменений
progingir 98eab61
лимит
progingir b5292b9
пробуем
progingir 80e7f12
опять пробуем
progingir 313816f
откат изменений
progingir da5e701
ижектю через конструктор
progingir f738fa6
сделала бины с маленькой буквы
progingir f0e464d
убрала аннотацию
progingir 8739351
стиль кода
progingir 3f33f52
убрала аннотацию
progingir 490817c
убрала еще ненужные аннотации
progingir 0d46144
убрала аннотацию @Qualifier
progingir 97c5632
убрала проверку айди, скорее всего, полетят тесты
progingir 7f213ed
пытаюсь внести count в запрос
progingir b5a841d
откат изменений
progingir 29db077
избавляюсь от лишнего парсинга
progingir d716acb
лишний парсинг
progingir 06af9ea
стиль
progingir bc332bd
опять
progingir 2a32abc
парсим напрямую через buffer
progingir 798bcba
ааа
progingir da95413
....
progingir 239d5dd
стиль
progingir f04cfc2
откат изменений
progingir 60500ad
sss
progingir 2c6864a
откат
progingir 0a9c5c1
правки
progingir bb81b4e
dd
progingir a44d1df
откат
progingir 3089811
опять класс по парсингу
progingir 265b785
откат
progingir File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
125 changes: 85 additions & 40 deletions
125
src/main/java/ru/yandex/practicum/filmorate/controller/FilmController.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,73 +1,118 @@ | ||
| package ru.yandex.practicum.filmorate.controller; | ||
|
|
||
| import com.fasterxml.jackson.databind.node.ObjectNode; | ||
| import jakarta.validation.Valid; | ||
| import org.springframework.beans.factory.annotation.Autowired; | ||
| import org.springframework.http.HttpStatus; | ||
| import org.springframework.http.ResponseEntity; | ||
| import org.springframework.web.bind.annotation.*; | ||
| import org.springframework.beans.factory.annotation.Autowired; | ||
| import ru.yandex.practicum.filmorate.exception.NotFoundException; | ||
| import ru.yandex.practicum.filmorate.model.Buffer; | ||
| import ru.yandex.practicum.filmorate.model.Film; | ||
| import ru.yandex.practicum.filmorate.service.FilmService; | ||
| import ru.yandex.practicum.filmorate.model.FilmResponse; | ||
| import ru.yandex.practicum.filmorate.service.FilmInterface; | ||
| import ru.yandex.practicum.filmorate.storage.film.FilmStorage; | ||
| import ru.yandex.practicum.filmorate.storage.user.UserStorage; | ||
|
|
||
| import java.util.Collection; | ||
| import java.util.Map; | ||
| import java.time.LocalDate; | ||
| import java.time.format.DateTimeFormatter; | ||
| import java.util.*; | ||
|
|
||
| @RestController | ||
| @RequestMapping("/films") | ||
| public class FilmController { | ||
|
|
||
| private final FilmService filmService; | ||
| private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd"); | ||
| private static final String DEFAULT_GENRE = "нет жанра"; | ||
|
|
||
| private final FilmStorage filmStorage; | ||
| private final UserStorage userStorage; | ||
| private final FilmInterface filmInterface; | ||
|
|
||
| @Autowired | ||
| public FilmController(FilmService filmService) { | ||
| this.filmService = filmService; | ||
| public FilmController( | ||
| FilmStorage filmStorage, | ||
| UserStorage userStorage, | ||
| FilmInterface filmInterface | ||
| ) { | ||
| this.filmStorage = filmStorage; | ||
| this.userStorage = userStorage; | ||
| this.filmInterface = filmInterface; | ||
| } | ||
|
|
||
| //создание фильма | ||
| @PostMapping | ||
| public Film createFilm(@Valid @RequestBody Film film) { | ||
| return filmService.createFilm(film); | ||
| @GetMapping | ||
| public List<Film> findAll() { | ||
| return filmStorage.findAll(); | ||
| } | ||
|
|
||
| //обновление фильма | ||
| @PutMapping | ||
| public Film update(@Valid @RequestBody Film film) { | ||
| return filmService.update(film); | ||
| @GetMapping("/{id}") | ||
| public FilmResponse findById(@PathVariable("id") Long id) { | ||
| return filmStorage.findById(id); | ||
| } | ||
|
|
||
| //получение всех фильмов | ||
| @GetMapping | ||
| public Collection<Film> getFilms() { | ||
| return filmService.getFilms(); | ||
| @PostMapping | ||
| @ResponseStatus(HttpStatus.CREATED) | ||
| public FilmResponse create(@Valid @RequestBody ObjectNode objectNode) { | ||
| Buffer buffer = parseObjectNodeToBuffer(objectNode); | ||
| return filmStorage.create(buffer); | ||
| } | ||
|
|
||
| //получение фильма по ID | ||
| @GetMapping("/{id}") | ||
| public Film getFilmById(@PathVariable Long id) { | ||
| return filmService.getFilmById(id); | ||
| @PutMapping | ||
| public FilmResponse update(@Valid @RequestBody ObjectNode objectNode) { | ||
| Buffer buffer = parseObjectNodeToBuffer(objectNode); | ||
| return filmStorage.update(buffer); | ||
| } | ||
|
|
||
| @PutMapping("/{id}/like/{userId}") | ||
| public ResponseEntity<?> addLike(@PathVariable Long id, @PathVariable Long userId) { | ||
| try { | ||
| filmService.addLike(id, userId); | ||
| return ResponseEntity.ok().build(); // Возвращаем 200 OK, если лайк добавлен | ||
| } catch (NotFoundException e) { | ||
| return ResponseEntity.status(HttpStatus.NOT_FOUND) | ||
| .body(Map.of("error", e.getMessage())); // Возвращаем 404 и JSON с ошибкой | ||
| } | ||
| public FilmResponse addLike(@Valid @PathVariable("id") Long id, @PathVariable("userId") Long userId) { | ||
| return filmInterface.addLike(userId, id); | ||
| } | ||
|
|
||
| //удаление лайка из фильма | ||
| @DeleteMapping("/{id}/like/{userId}") | ||
| public ResponseEntity<Void> removeLike(@PathVariable Long id, @PathVariable Long userId) { | ||
| filmService.removeLike(id, userId); | ||
| return ResponseEntity.ok().build(); | ||
| public FilmResponse delLike(@Valid @PathVariable("id") Long id, @PathVariable("userId") Long userId) { | ||
| return filmInterface.delLike(userId, id); | ||
| } | ||
|
|
||
| //получение популярных фильмов | ||
| @GetMapping("/popular") | ||
| public Collection<Film> getTopFilms(@RequestParam(defaultValue = "10") int count) { | ||
| return filmService.getTopFilms(count); | ||
| public LinkedHashSet<FilmResponse> viewRating(@RequestParam(defaultValue = "10") Long count) { | ||
| return filmInterface.viewRating(count); | ||
| } | ||
|
|
||
| /** | ||
| * преобразует json объект в объект Buffer | ||
| * | ||
| * @param objectNode json объект | ||
| * @return объект Buffer | ||
| */ | ||
| private Buffer parseObjectNodeToBuffer(ObjectNode objectNode) { | ||
| Long id = objectNode.has("id") ? objectNode.get("id").asLong() : 0L; | ||
| String name = objectNode.get("name").asText(); | ||
| String description = objectNode.get("description").asText(); | ||
| String releaseDate = objectNode.get("releaseDate").asText(); | ||
| Integer duration = objectNode.get("duration").asInt(); | ||
| List<String> mpa = objectNode.get("mpa").findValuesAsText("id"); | ||
| List<String> genres = extractGenresFromObjectNode(objectNode); | ||
|
|
||
| return Buffer.of( | ||
| id, | ||
| name, | ||
| description, | ||
| LocalDate.parse(releaseDate, DATE_FORMATTER), | ||
| duration, | ||
| genres, | ||
| Long.valueOf(mpa.get(0)) | ||
| ); | ||
| } | ||
|
|
||
| /** | ||
| * извлекает список жанров из json объекта | ||
| * | ||
| * @param objectNode json объект | ||
| * @return список жанров | ||
| */ | ||
| private List<String> extractGenresFromObjectNode(ObjectNode objectNode) { | ||
| try { | ||
| return objectNode.get("genres").findValuesAsText("id"); | ||
| } catch (NullPointerException e) { | ||
| return List.of(DEFAULT_GENRE); | ||
| } | ||
| } | ||
| } | ||
37 changes: 37 additions & 0 deletions
37
src/main/java/ru/yandex/practicum/filmorate/controller/GenreController.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| package ru.yandex.practicum.filmorate.controller; | ||
|
|
||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.web.bind.annotation.*; | ||
| import ru.yandex.practicum.filmorate.model.Genre; | ||
| import ru.yandex.practicum.filmorate.service.GenreService; | ||
|
|
||
| import java.util.List; | ||
|
|
||
| @RestController | ||
| @RequestMapping("/genres") | ||
| @RequiredArgsConstructor | ||
| public class GenreController { | ||
|
|
||
| private final GenreService genreService; | ||
|
|
||
| /** | ||
| * получить жанр по его идентификатору | ||
| * | ||
| * @param id идентификатор жанра | ||
| * @return объект жанра | ||
| */ | ||
| @GetMapping("/{id}") | ||
| public Genre getGenreById(@PathVariable Long id) { | ||
| return genreService.getGenreById(id); | ||
| } | ||
|
|
||
| /** | ||
| * получить список всех жанров | ||
| * | ||
| * @return список всех жанров | ||
| */ | ||
| @GetMapping | ||
| public List<Genre> getAllGenres() { | ||
| return genreService.getAllGenres(); | ||
| } | ||
| } |
37 changes: 37 additions & 0 deletions
37
src/main/java/ru/yandex/practicum/filmorate/controller/MpaController.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| package ru.yandex.practicum.filmorate.controller; | ||
|
|
||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.web.bind.annotation.*; | ||
| import ru.yandex.practicum.filmorate.model.Mpa; | ||
| import ru.yandex.practicum.filmorate.service.MpaService; | ||
|
|
||
| import java.util.List; | ||
|
|
||
| @RestController | ||
| @RequestMapping("/mpa") | ||
| @RequiredArgsConstructor | ||
| public class MpaController { | ||
|
|
||
| private final MpaService mpaService; | ||
|
|
||
| /** | ||
| * получить рейтинг mpa по его идентификатору | ||
| * | ||
| * @param id идентификатор рейтинга mpa | ||
| * @return объект рейтинга mpa | ||
| */ | ||
| @GetMapping("/{id}") | ||
| public Mpa getMpaById(@PathVariable Long id) { | ||
| return mpaService.getMpaById(id); | ||
| } | ||
|
|
||
| /** | ||
| * получить список всех рейтингов mpa | ||
| * | ||
| * @return список всех рейтингов mpa | ||
| */ | ||
| @GetMapping | ||
| public List<Mpa> getAllMpa() { | ||
| return mpaService.getAllMpa(); | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Кажется лишней манипуляцией с данными
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
тесты падают с ошибками без парсинга, пробовала без него, все полетело