Write validation for createVotesRequest

This commit is contained in:
2025-01-02 18:12:48 +01:00
parent d251909ee7
commit 9efe9a3537
2 changed files with 23 additions and 3 deletions

View File

@ -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
}
}

View File

@ -236,7 +236,6 @@ components:
minLength: 1
tokens:
type: integer
minimum: 1
ErrorResponse:
type: object