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
9 changes: 3 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ type Handler struct {

func (h *Handler) Register(r chi.Router) {
r.Get("/", h.list)
r.With(m.Validate[form.BookForm](h.validator)).Post("/", h.create)
r.With(m.Validate[Form](h.validator)).Post("/", h.create)
r.Get("/{id}", h.read)
r.With(m.Validate[form.BookForm](h.validator)).Put("/{id}", h.update)
r.With(m.Validate[Form](h.validator)).Put("/{id}", h.update)
r.Delete("/{id}", h.delete)
}

Expand Down Expand Up @@ -190,14 +190,11 @@ app-1 | {"level":"info","request_id":"d5mqjmhqvtmc73foh3dg","received_time":"20
│ └── migrations
│ └── 00001_create_books_table.sql
│
├── form # 💡Form validation middleware rely on this and pkg folder only
│ └── book.go
│
├── app
│ ├── book
│ │ ├── bookrepo # 💡generated with gorm-cli via the interface in book/repository.go
│ │ │ └── repository.go
│ │ ├── form_util.go
│ │ ├── form.go # 💡validate via Go generics based form validation middleware
│ │ ├── handler.go
│ │ └── repository.go
│ └── router
Expand Down
35 changes: 35 additions & 0 deletions app/book/form.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package book

import (
"time"

"github.com/google/uuid"

"myapp/model"
)

type Form struct {
Title string `json:"title" validate:"required,max=255"`
PublishedDate string `json:"published_date" validate:"required,datetime=2006-01-02"`
Description string `json:"description"`
ImageURL string `json:"image_url" validate:"url"`
Status string `json:"status" validate:"required,oneof=pending verified"`
}

func (f *Form) ToCreateModel() *model.Book {
return f.ToUpdateModel(uuid.New())
}

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

return &model.Book{
ID: id,
PublishedDate: model.CivilDate(pubDate),
Title: f.Title,
ImageURL: f.ImageURL,
Description: f.Description,
Status: *status,
}
}
28 changes: 0 additions & 28 deletions app/book/form_util.go

This file was deleted.

23 changes: 11 additions & 12 deletions app/book/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import (
"gorm.io/gorm"

"myapp/app/book/bookrepo"
"myapp/form"
"myapp/model"
"myapp/pkg/ctxutil"
e "myapp/pkg/errors"
Expand All @@ -34,9 +33,9 @@ func New(validator *validator.Validate, db *gorm.DB) *Handler {

func (h *Handler) Register(r chi.Router) {
r.Get("/", h.list)
r.With(m.Validate[form.BookForm](h.validator)).Post("/", h.create)
r.With(m.Validate[Form](h.validator)).Post("/", h.create)
r.Get("/{id}", h.read)
r.With(m.Validate[form.BookForm](h.validator)).Put("/{id}", h.update)
r.With(m.Validate[Form](h.validator)).Put("/{id}", h.update)
r.Delete("/{id}", h.delete)
}

Expand Down Expand Up @@ -83,7 +82,7 @@ func (h *Handler) list(w http.ResponseWriter, r *http.Request) {
// @tags books
// @accept json
// @produce json
// @param body body form.BookForm true "Book form"
// @param body body Form true "Book form"
// @success 201 {object} model.Book
// @failure 400 {object} e.Error
// @failure 422 {object} e.Errors
Expand All @@ -93,14 +92,14 @@ func (h *Handler) create(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
logger := hlog.FromRequest(r)

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

book, err := h.bookRepo.CreateBook(ctx, createFormToModel(&ctxForm))
book, err := h.bookRepo.CreateBook(ctx, ctxForm.ToCreateModel())
if err != nil {
logger.Error().Err(err).Msg("")
e.ServerError(w, e.RespDBDataInsertFailure)
Expand Down Expand Up @@ -166,8 +165,8 @@ func (h *Handler) read(w http.ResponseWriter, r *http.Request) {
// @tags books
// @accept json
// @produce json
// @param id path string true "Book ID"
// @param body body form.BookForm true "Book form"
// @param id path string true "Book ID"
// @param body body Form true "Book form"
// @success 200 {object} model.Book
// @failure 400 {object} e.Error
// @failure 404
Expand All @@ -184,14 +183,14 @@ func (h *Handler) update(w http.ResponseWriter, r *http.Request) {
return
}

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

book, err := h.bookRepo.UpdateBook(ctx, updateFormToModel(&ctxForm, id))
book, err := h.bookRepo.UpdateBook(ctx, ctxForm.ToUpdateModel(id))
if err != nil {
logger.Error().Err(err).Msg("")
e.ServerError(w, e.RespDBDataUpdateFailure)
Expand Down
11 changes: 0 additions & 11 deletions form/book.go

This file was deleted.

6 changes: 3 additions & 3 deletions openapi.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
definitions:
form.BookForm:
app_book.Form:
properties:
description:
type: string
Expand Down Expand Up @@ -118,7 +118,7 @@ paths:
name: body
required: true
schema:
$ref: '#/definitions/form.BookForm'
$ref: '#/definitions/app_book.Form'
produces:
- application/json
responses:
Expand Down Expand Up @@ -215,7 +215,7 @@ paths:
name: body
required: true
schema:
$ref: '#/definitions/form.BookForm'
$ref: '#/definitions/app_book.Form'
produces:
- application/json
responses:
Expand Down