profession - add validation to UpdateOne and Store methods

This commit is contained in:
Dawid Wysokiński 2021-02-27 12:40:06 +01:00
parent 3414f8cbb5
commit 532cf70b84
3 changed files with 43 additions and 3 deletions

View File

@ -0,0 +1,6 @@
package profession
const (
DefaultLimit = 100
MaxNameLength = 100
)

View File

@ -1,6 +1,9 @@
package usecase
const (
messageInvalidID = "Niepoprawne ID."
messageItemNotFound = "Nie znaleziono zawodu."
messageInvalidID = "Niepoprawne ID."
messageItemNotFound = "Nie znaleziono zawodu."
messageEmptyPayload = "Nie wprowadzono jakichkolwiek danych."
messageNameIsRequired = "Nazwa zawodu jest polem wymaganym."
messageNameIsTooLong = "Nazwa zawodu może się składać z maksymalnie %d znaków."
)

View File

@ -3,6 +3,7 @@ package usecase
import (
"context"
"fmt"
"strings"
"github.com/zdam-egzamin-zawodowy/backend/internal/models"
"github.com/zdam-egzamin-zawodowy/backend/internal/profession"
@ -27,12 +28,18 @@ func New(cfg *Config) (profession.Usecase, error) {
}
func (ucase *usecase) Store(ctx context.Context, input *models.ProfessionInput) (*models.Profession, error) {
if err := ucase.validateInput(input, validateOptions{false}); err != nil {
return nil, err
}
return ucase.professionRepository.Store(ctx, input)
}
func (ucase *usecase) UpdateOne(ctx context.Context, id int, input *models.ProfessionInput) (*models.Profession, error) {
if id <= 0 {
return nil, fmt.Errorf(messageInvalidID)
}
if err := ucase.validateInput(input, validateOptions{true}); err != nil {
}
items, err := ucase.professionRepository.UpdateMany(ctx,
&models.ProfessionFilter{
@ -55,7 +62,7 @@ func (ucase *usecase) Delete(ctx context.Context, f *models.ProfessionFilter) ([
func (ucase *usecase) Fetch(ctx context.Context, cfg *profession.FetchConfig) ([]*models.Profession, int, error) {
if cfg == nil {
cfg = &profession.FetchConfig{
Limit: 100,
Limit: profession.DefaultLimit,
Count: true,
}
}
@ -96,3 +103,27 @@ func (ucase *usecase) GetBySlug(ctx context.Context, slug string) (*models.Profe
}
return items[0], nil
}
type validateOptions struct {
nameCanBeNil bool
}
func (ucase *usecase) validateInput(input *models.ProfessionInput, opts validateOptions) error {
if input.IsEmpty() {
return fmt.Errorf(messageEmptyPayload)
}
if input.Name != nil {
trimmedName := strings.TrimSpace(*input.Name)
input.Name = &trimmedName
if trimmedName == "" {
return fmt.Errorf(messageNameIsRequired)
} else if len(trimmedName) > profession.MaxNameLength {
return fmt.Errorf(messageNameIsTooLong, profession.MaxNameLength)
}
} else if !opts.nameCanBeNil {
return fmt.Errorf(messageNameIsRequired)
}
return nil
}