Files
oslstats/internal/handlers/team_shortnames_unique.go
2026-02-12 21:10:49 +11:00

58 lines
1.4 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/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 *bun.DB,
) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
getter, err := validation.ParseForm(r)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
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 == "" {
w.WriteHeader(http.StatusOK)
return
}
if shortName == altShortName {
w.WriteHeader(http.StatusConflict)
return
}
var isUnique bool
if ok := db.WithReadTx(s, w, r, conn, 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 {
w.WriteHeader(http.StatusOK)
} else {
w.WriteHeader(http.StatusConflict)
}
})
}