Skip to content
Snippets Groups Projects
Commit 8489e58d authored by ko_oler's avatar ko_oler
Browse files

правки по ПР:

- ошибки перенесены в переменные/константы
- часть ошибки убрана в детали
- добавлен Trim и проверка на пустоту в ValidateID()
parent dd6ade21
No related branches found
No related tags found
No related merge requests found
...@@ -2,36 +2,47 @@ package id ...@@ -2,36 +2,47 @@ package id
import ( import (
"regexp" "regexp"
"strings"
"git.perx.ru/perxis/perxis-go/pkg/errors" "git.perx.ru/perxis/perxis-go/pkg/errors"
"github.com/rs/xid" "github.com/rs/xid"
) )
const ( const (
IDMaxLength = 64 MaxLengthID = 64
NameMaxLength = 256 MaxLengthName = 256
) )
var isValidID = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9-_]*$`).MatchString var (
ErrEmptyID = errors.New("empty ID")
ErrNotValidID = errors.New("id contains invalid characters")
ErrLongID = errors.New("id too long (max 64 symbols)")
ErrLongName = errors.New("name too long (max 256 symbols)")
isValidID = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9-_]*$`).MatchString
)
func GenerateNewID() string { func GenerateNewID() string {
return xid.New().String() return xid.New().String()
} }
func ValidateID(id string) error { func ValidateID(id string) error {
if len(id) > IDMaxLength { trimmedID := strings.TrimSpace(id)
return errors.New("invalid id: too long (max 64 symbols)") if trimmedID == "" {
return ErrEmptyID
}
if len(trimmedID) > MaxLengthID {
return ErrLongID
} }
if !isValidID(id) { if !isValidID(trimmedID) {
return errors.New("invalid id: must begin with latin letters and contain latin letters, numbers or '-', '_'") return errors.WithDetail(ErrNotValidID, "must begin with latin letters and contain latin letters, numbers or '-', '_'")
} }
return nil return nil
} }
func ValidateName(name string) error { func ValidateName(name string) error {
if len(name) > NameMaxLength { if len(name) > MaxLengthName {
return errors.New("invalid name: too long (max 256 symbols)") return ErrLongName
} }
return nil return nil
......
...@@ -28,11 +28,6 @@ func TestValidateID(t *testing.T) { ...@@ -28,11 +28,6 @@ func TestValidateID(t *testing.T) {
"1test", "1test",
true, true,
}, },
{
"Fail, ID starts with whitespace",
" test",
true,
},
{ {
"Fail, ID to long", "Fail, ID to long",
"9QoulAlFbIcnQYLSudMistN1IczCWrXUTtN5EgNQJd516DN9UjXYJxieJ1RcsNcs1", "9QoulAlFbIcnQYLSudMistN1IczCWrXUTtN5EgNQJd516DN9UjXYJxieJ1RcsNcs1",
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment