diff --git a/cmd/web/handlers.go b/cmd/web/handlers.go index 9b9880c..402a470 100644 --- a/cmd/web/handlers.go +++ b/cmd/web/handlers.go @@ -101,11 +101,32 @@ func randomVoterIdentity() string { return string(b) } -type createVoteRequestWithValidator struct { +type createVotesRequestWithValidator struct { api.CreateVotesRequest validator.Validator } -func (app *application) createVote(w http.ResponseWriter, r *http.Request) { +func (r *createVotesRequestWithValidator) isValid() bool { + r.CheckField(validator.NotBlank(*r.VoterIdentity), "voterIdentity", "must not be blank") + r.CheckField(validator.GreaterThan(*r.ElectionId, 0), "electionId", "must be greater than 0") + for _, choice := range *r.Choices { + r.CheckField(validator.NotBlank(*choice.ChoiceText), "choiceText", "must not be blank") + } + + return r.Valid() +} + +func (app *application) createVote(w http.ResponseWriter, r *http.Request) { + var request createVotesRequestWithValidator + + if err := app.unmarshalRequest(r, &request); err != nil { + app.clientError(w, http.StatusBadRequest, err.Error()) + return + } + + if !request.isValid() { + app.unprocessableEntityError(w, request.Validator) + return + } } diff --git a/cmd/web/openapi.yml b/cmd/web/openapi.yml index 0225430..c294c3d 100644 --- a/cmd/web/openapi.yml +++ b/cmd/web/openapi.yml @@ -236,7 +236,6 @@ components: minLength: 1 tokens: type: integer - minimum: 1 ErrorResponse: type: object