59 lines
1.5 KiB
Go
59 lines
1.5 KiB
Go
package handlers
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
|
|
"git.haelnorr.com/h/golib/hws"
|
|
"git.haelnorr.com/h/oslstats/internal/db"
|
|
"git.haelnorr.com/h/oslstats/internal/respond"
|
|
"git.haelnorr.com/h/oslstats/internal/validation"
|
|
"github.com/pkg/errors"
|
|
"github.com/uptrace/bun"
|
|
)
|
|
|
|
// IsTeamShortNamesUnique checks if the combination of short_name and alt_short_name is unique
|
|
// and also validates that they are different from each other
|
|
func IsTeamShortNamesUnique(
|
|
s *hws.Server,
|
|
conn *db.DB,
|
|
) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
getter, err := validation.ParseForm(r)
|
|
if err != nil {
|
|
respond.BadRequest(w, err)
|
|
return
|
|
}
|
|
|
|
shortName := getter.String("short_name").TrimSpace().ToUpper().MaxLength(3).Value
|
|
altShortName := getter.String("alt_short_name").TrimSpace().ToUpper().MaxLength(3).Value
|
|
|
|
if shortName == "" || altShortName == "" {
|
|
respond.OK(w)
|
|
return
|
|
}
|
|
|
|
if shortName == altShortName {
|
|
respond.Conflict(w, errors.New("short names cannot be the same"))
|
|
return
|
|
}
|
|
|
|
var isUnique bool
|
|
if ok := conn.WithReadTx(s, w, r, func(ctx context.Context, tx bun.Tx) (bool, error) {
|
|
isUnique, err = db.TeamShortNamesUnique(ctx, tx, shortName, altShortName)
|
|
if err != nil {
|
|
return false, errors.Wrap(err, "db.TeamShortNamesUnique")
|
|
}
|
|
return true, nil
|
|
}); !ok {
|
|
return
|
|
}
|
|
|
|
if isUnique {
|
|
respond.OK(w)
|
|
} else {
|
|
respond.Conflict(w, errors.New("short name combination is taken"))
|
|
}
|
|
})
|
|
}
|