From bd844e3c22dba6017559f4fffd02faaf458bf17f Mon Sep 17 00:00:00 2001 From: ergz Date: Fri, 18 Aug 2023 14:58:11 -0700 Subject: [PATCH] adds validation checks json in create movie --- cmd/api/errors.go | 4 ++++ cmd/api/movies.go | 25 +++++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/cmd/api/errors.go b/cmd/api/errors.go index f597b8c..8b4d11e 100644 --- a/cmd/api/errors.go +++ b/cmd/api/errors.go @@ -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) +} diff --git a/cmd/api/movies.go b/cmd/api/movies.go index 5682c6b..7b7c4f0 100644 --- a/cmd/api/movies.go +++ b/cmd/api/movies.go @@ -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) }