package handlers import ( "context" "fmt" "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" ) // IsUnique creates a handler that checks field uniqueness // Returns 200 OK if unique, 409 Conflict if not unique func IsUnique( s *hws.Server, conn *db.DB, model any, field string, ) 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 } value := getter.String(field).TrimSpace().Required().Value if !getter.Validate() { respond.BadRequest(w, err) return } unique := false if ok := conn.WithNotifyTx(s, w, r, func(ctx context.Context, tx bun.Tx) (bool, error) { unique, err = db.IsUnique(ctx, tx, model, field, value) if err != nil { return false, errors.Wrap(err, "db.IsUnique") } return true, nil }); !ok { return } if unique { respond.OK(w) } else { err := fmt.Errorf("'%s' is not unique for field '%s'", value, field) respond.Conflict(w, err) } }) }