From ed42b78cda0193d990781fc8c4a2c7e7f8210296 Mon Sep 17 00:00:00 2001 From: Shuhrat Tultaganov Date: Sat, 28 Jan 2023 22:04:23 +0300 Subject: [PATCH] Add headler for find by name in db --- internal/bd/filmsrepo.go | 23 ++++++++++++++++++++++- internal/restserver/filmhandle.go | 16 ++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/internal/bd/filmsrepo.go b/internal/bd/filmsrepo.go index b045c3b..cf8bd67 100644 --- a/internal/bd/filmsrepo.go +++ b/internal/bd/filmsrepo.go @@ -81,8 +81,29 @@ func (f *Filmsrepo) FindById(id string) (*model.Films, error) { } if rows.Err() != nil { - return nil, err + return nil, rows.Err() } return &buff, nil } + +func (f *Filmsrepo) FindByName(name string) (*[]model.Films, error) { + var films []model.Films + rows, err := f.db.db.Query(context.Background(), "SELECT * FROM films WHERE ru_title LIKE '%"+name+"%'") + if err != nil { + return nil, err + } + + for rows.Next() { + var film model.Films + rows.Scan(&film.Id, &film.Ru_title, &film.Orig_title, &film.Imdb_id, &film.Kinopoisk_id, + &film.PosterUrl, &film.PosterUrlPreview, &film.Countries, &film.Genres, &film.Year, + &film.Description, &film.RatingKinopoisk, &film.RatingImdb, &film.Iframe_src, &film.RatingImdbVoteCount, + &film.RatingKinopoiskVoteCount, &film.Media) + if rows.Err() != nil { + return nil, rows.Err() + } + films = append(films, film) + } + return &films, nil +} diff --git a/internal/restserver/filmhandle.go b/internal/restserver/filmhandle.go index e1fcd8a..0565165 100644 --- a/internal/restserver/filmhandle.go +++ b/internal/restserver/filmhandle.go @@ -15,6 +15,7 @@ func (r *RestServer) configureRouterFilms() { r.router.HandleFunc("/api/hello", r.HandleHello()).Methods("GET") r.router.HandleFunc("/api/films", r.HendleFindAll()).Methods("GET") r.router.HandleFunc("/api/films/{id:[0-9]+}", r.HendleFindID()).Methods("GET") + r.router.HandleFunc("/api/films/{name}", r.HeandleFilmsFindName()).Methods("GET") } func (r *RestServer) HandleHello() http.HandlerFunc { @@ -55,6 +56,21 @@ func (r *RestServer) HendleFindAll() http.HandlerFunc { } } +func (r *RestServer) HeandleFilmsFindName() http.HandlerFunc { + return func(w http.ResponseWriter, res *http.Request) { + name := mux.Vars(res)["name"] + films, err := r.db.Films().FindByName(name) + if err != nil { + r.logger.Errorln(err) + } + jsonData, err := json.Marshal(films) + if err != nil { + r.logger.Errorln(err) + } + io.WriteString(w, string(jsonData)) + } +} + func (r *RestServer) HendleFindID() http.HandlerFunc { return func(w http.ResponseWriter, res *http.Request) { id := mux.Vars(res)["id"]