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
6 changes: 3 additions & 3 deletions app/book/form_util.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ import (
"myapp/model"
)

func CreateFormToModel(f *form.BookForm) *model.Book {
return UpdateFormToModel(f, uuid.New())
func createFormToModel(f *form.BookForm) *model.Book {
return updateFormToModel(f, uuid.New())
}

func UpdateFormToModel(f *form.BookForm, id uuid.UUID) *model.Book {
func updateFormToModel(f *form.BookForm, id uuid.UUID) *model.Book {
pubDate, _ := time.Parse("2006-01-02", f.PublishedDate)
status, _ := model.ParseBookStatus(f.Status)

Expand Down
41 changes: 24 additions & 17 deletions app/book/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,23 +16,30 @@ import (
"myapp/model"
"myapp/pkg/ctxutil"
e "myapp/pkg/errors"
m "myapp/pkg/middleware"
"myapp/pkg/paramsutil"
)

const MsgErrCTXValidatedFormNotFound = "context validated form not found"

type API struct {
type Handler struct {
validator *validator.Validate
bookRepo IBookRepo
}

func New(validator *validator.Validate, db *gorm.DB) *API {
return &API{
func New(validator *validator.Validate, db *gorm.DB) *Handler {
return &Handler{
validator: validator,
bookRepo: bookrepo.IBookRepo[model.Book](db),
}
}

func (h *Handler) Register(r chi.Router) {
r.Get("/", h.List)
r.With(m.Validate[form.BookForm](h.validator)).Post("/", h.Create)
r.Get("/{id}", h.Read)
r.With(m.Validate[form.BookForm](h.validator)).Put("/{id}", h.Update)
r.Delete("/{id}", h.Delete)
}

// List godoc
//
// @summary List books
Expand All @@ -45,12 +52,12 @@ func New(validator *validator.Validate, db *gorm.DB) *API {
// @success 200 {array} model.Book
// @failure 500 {object} e.Error
// @router /books [get]
func (a *API) List(w http.ResponseWriter, r *http.Request) {
func (h *Handler) List(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
logger := hlog.FromRequest(r)

limit, offset := paramsutil.LimitOffset(r)
books, err := a.bookRepo.ListBooks(ctx, limit, offset)
books, err := h.bookRepo.ListBooks(ctx, limit, offset)
if err != nil {
logger.Error().Err(err).Msg("")
e.ServerError(w, e.RespDBDataAccessFailure)
Expand Down Expand Up @@ -82,18 +89,18 @@ func (a *API) List(w http.ResponseWriter, r *http.Request) {
// @failure 422 {object} e.Errors
// @failure 500 {object} e.Error
// @router /books [post]
func (a *API) Create(w http.ResponseWriter, r *http.Request) {
func (h *Handler) Create(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
logger := hlog.FromRequest(r)

ctxForm, ok := ctxutil.ValidatedForm[form.BookForm](ctx)
if !ok {
logger.Error().Msg(MsgErrCTXValidatedFormNotFound)
logger.Error().Msg(form.LogErrCTXValidatedFormNotFound)
e.ServerError(w, e.RespValidatedFormNotFound)
return
}

book, err := a.bookRepo.CreateBook(ctx, CreateFormToModel(&ctxForm))
book, err := h.bookRepo.CreateBook(ctx, createFormToModel(&ctxForm))
if err != nil {
logger.Error().Err(err).Msg("")
e.ServerError(w, e.RespDBDataInsertFailure)
Expand Down Expand Up @@ -123,7 +130,7 @@ func (a *API) Create(w http.ResponseWriter, r *http.Request) {
// @failure 404
// @failure 500 {object} e.Error
// @router /books/{id} [get]
func (a *API) Read(w http.ResponseWriter, r *http.Request) {
func (h *Handler) Read(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
logger := hlog.FromRequest(r)

Expand All @@ -133,7 +140,7 @@ func (a *API) Read(w http.ResponseWriter, r *http.Request) {
return
}

book, err := a.bookRepo.ReadBook(ctx, id)
book, err := h.bookRepo.ReadBook(ctx, id)
if err != nil {
logger.Error().Err(err).Msg("")
e.ServerError(w, e.RespDBDataAccessFailure)
Expand Down Expand Up @@ -167,7 +174,7 @@ func (a *API) Read(w http.ResponseWriter, r *http.Request) {
// @failure 422 {object} e.Errors
// @failure 500 {object} e.Error
// @router /books/{id} [put]
func (a *API) Update(w http.ResponseWriter, r *http.Request) {
func (h *Handler) Update(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
logger := hlog.FromRequest(r)

Expand All @@ -179,12 +186,12 @@ func (a *API) Update(w http.ResponseWriter, r *http.Request) {

ctxForm, ok := ctxutil.ValidatedForm[form.BookForm](ctx)
if !ok {
logger.Error().Msg(MsgErrCTXValidatedFormNotFound)
logger.Error().Msg(form.LogErrCTXValidatedFormNotFound)
e.ServerError(w, e.RespValidatedFormNotFound)
return
}

book, err := a.bookRepo.UpdateBook(ctx, UpdateFormToModel(&ctxForm, id))
book, err := h.bookRepo.UpdateBook(ctx, updateFormToModel(&ctxForm, id))
if err != nil {
logger.Error().Err(err).Msg("")
e.ServerError(w, e.RespDBDataUpdateFailure)
Expand Down Expand Up @@ -218,7 +225,7 @@ func (a *API) Update(w http.ResponseWriter, r *http.Request) {
// @failure 404
// @failure 500 {object} e.Error
// @router /books/{id} [delete]
func (a *API) Delete(w http.ResponseWriter, r *http.Request) {
func (h *Handler) Delete(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
logger := hlog.FromRequest(r)

Expand All @@ -228,7 +235,7 @@ func (a *API) Delete(w http.ResponseWriter, r *http.Request) {
return
}

isDeleted, err := a.bookRepo.DeleteBook(ctx, id)
isDeleted, err := h.bookRepo.DeleteBook(ctx, id)
if err != nil {
logger.Error().Err(err).Msg("")
e.ServerError(w, e.RespDBDataRemoveFailure)
Expand Down
9 changes: 1 addition & 8 deletions app/router/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (
"gorm.io/gorm"

"myapp/app/book"
"myapp/form"
m "myapp/pkg/middleware"
mrl "myapp/pkg/middleware/requestlog"
)
Expand All @@ -26,13 +25,7 @@ func New(l *zerolog.Logger, v *validator.Validate, db *gorm.DB) *chi.Mux {
r.Use(hlog.RequestIDHandler("request_id", "X-Request-ID"))
r.Use(mrl.NewHandler)
r.Use(m.ContentTypeJSON)

bookAPI := book.New(v, db)
r.Get("/books", bookAPI.List)
r.With(m.Validate[form.BookForm](v)).Post("/books", bookAPI.Create)
r.Get("/books/{id}", bookAPI.Read)
r.With(m.Validate[form.BookForm](v)).Put("/books/{id}", bookAPI.Update)
r.Delete("/books/{id}", bookAPI.Delete)
r.Route("/books", book.New(v, db).Register)
})

return r
Expand Down
2 changes: 2 additions & 0 deletions form/book.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package form

const LogErrCTXValidatedFormNotFound = "context validated form not found"

type BookForm struct {
Title string `json:"title" validate:"required,max=255"`
PublishedDate string `json:"published_date" validate:"required,datetime=2006-01-02"`
Expand Down