From f6bca0590fb583d935187d99fda4f8258860b5e2 Mon Sep 17 00:00:00 2001 From: Shuhrat Tultaganov Date: Thu, 26 Jan 2023 22:07:44 +0300 Subject: [PATCH] Add get count all items from db, and review result struct --- internal/bd/filmsrepo.go | 13 +++++++++++++ internal/restserver/filmhandle.go | 23 +++++++++++++++++++---- internal/restserver/resultStruct/films.go | 10 ++++++++++ 3 files changed, 42 insertions(+), 4 deletions(-) create mode 100644 internal/restserver/resultStruct/films.go diff --git a/internal/bd/filmsrepo.go b/internal/bd/filmsrepo.go index 787eeee..b045c3b 100644 --- a/internal/bd/filmsrepo.go +++ b/internal/bd/filmsrepo.go @@ -51,6 +51,19 @@ func (f *Filmsrepo) FindByAll() (*[]model.Films, error) { return &buffs, nil } +func (f *Filmsrepo) GetCountFilms() (*int, error) { + rows, err := f.db.db.Query(context.Background(), "SELECT count(*) FROM films") + var count int + if err != nil { + return nil, err + } + + for rows.Next() { + rows.Scan(&count) + } + return &count, nil +} + func (f *Filmsrepo) FindById(id string) (*model.Films, error) { query := fmt.Sprintf("SELECT * FROM films WHERE Id = %s;", id) var buff model.Films diff --git a/internal/restserver/filmhandle.go b/internal/restserver/filmhandle.go index 33f48f8..e1fcd8a 100644 --- a/internal/restserver/filmhandle.go +++ b/internal/restserver/filmhandle.go @@ -5,7 +5,9 @@ import ( "fmt" "io" "net/http" + "strconv" + resultstruct "git.ukamnya.ru/stulyaganov/RestApi/internal/restserver/resultStruct" "github.com/gorilla/mux" ) @@ -20,17 +22,30 @@ func (r *RestServer) HandleHello() http.HandlerFunc { return func(w http.ResponseWriter, res *http.Request) { id := res.URL.Query().Get("id") fmt.Println(id) - io.WriteString(w, id) + cout, err := r.db.Films().GetCountFilms() + if err != nil { + r.logger.Errorln(err) + } + io.WriteString(w, strconv.Itoa(*cout)) } } func (r *RestServer) HendleFindAll() http.HandlerFunc { - film, err := r.db.Films().FindByAll() + var filmData resultstruct.Films + data, err := r.db.Films().FindByAll() if err != nil { r.logger.Errorln(err) } - - jsonData, err := json.Marshal(film) + cout, err := r.db.Films().GetCountFilms() + if err != nil { + r.logger.Errorln(err) + filmData.Result = false + } else { + filmData.Result = true + filmData.Data = *data + filmData.LastPage = *cout + } + jsonData, err := json.Marshal(filmData) if err != nil { r.logger.Errorln(err) } diff --git a/internal/restserver/resultStruct/films.go b/internal/restserver/resultStruct/films.go new file mode 100644 index 0000000..f67a3a4 --- /dev/null +++ b/internal/restserver/resultStruct/films.go @@ -0,0 +1,10 @@ +package resultstruct + +import "git.ukamnya.ru/stulyaganov/RestApi/internal/bd/model" + +type Films struct { + Result bool + Data []model.Films + Page int + LastPage int +}