adds validation checks json in create movie

This commit is contained in:
Emanuel Rodriguez 2023-08-18 14:58:11 -07:00
parent d75f38c364
commit bd844e3c22
2 changed files with 29 additions and 0 deletions

View File

@ -39,3 +39,7 @@ func (app *application) methodNotAllowedResponse(w http.ResponseWriter, r *http.
func (app *application) badRequestResponse(w http.ResponseWriter, r *http.Request, err error) {
app.errorResponse(w, r, http.StatusBadRequest, err.Error())
}
func (app *application) failedValidationResponse(w http.ResponseWriter, r *http.Request, errors map[string]string) {
app.errorResponse(w, r, http.StatusUnprocessableEntity, errors)
}

View File

@ -6,6 +6,7 @@ import (
"time"
"greenlight.ergz/internal/data"
"greenlight.ergz/internal/validator"
)
func (app *application) createMovieHandler(w http.ResponseWriter, r *http.Request) {
@ -22,6 +23,30 @@ func (app *application) createMovieHandler(w http.ResponseWriter, r *http.Reques
return
}
v := validator.New()
// validate title
v.Check(input.Title != "", "title", "must be provided")
v.Check(len(input.Title) <= 500, "title", "must not be more than 500 bytes")
// validate the year
v.Check(input.Year != 0, "year", "must be provided")
v.Check(input.Year >= 1888, "year", "must be greater than 1888")
v.Check(input.Year <= int32(time.Now().Year()), "year", "must not be in the future")
v.Check(input.Runtime != 0, "runtime", "must be provided")
v.Check(input.Runtime > 0, "runtime", "must be a positive integer")
v.Check(input.Genres != nil, "genres", "must be provided")
v.Check(len(input.Genres) >= 1, "genres", "at least one genre must be provided")
v.Check(len(input.Genres) <= 5, "genres", "no more than 5 genres can be provided")
v.Check(validator.Unique(input.Genres), "genres", "must not contain duplicate genre")
if !v.Valid() {
app.failedValidationResponse(w, r, v.Errors)
return
}
fmt.Fprintf(w, "%+v\n", input)
}