refactored for maintainability
This commit is contained in:
49
internal/handlers/isunique.go
Normal file
49
internal/handlers/isunique.go
Normal file
@@ -0,0 +1,49 @@
|
||||
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"
|
||||
)
|
||||
|
||||
// IsUnique creates a handler that checks field uniqueness
|
||||
// Returns 200 OK if unique, 409 Conflict if not unique
|
||||
func IsUnique(
|
||||
s *hws.Server,
|
||||
conn *bun.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 {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
value := getter.String(field).TrimSpace().Required().Value
|
||||
if !getter.Validate() {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
unique := false
|
||||
if ok := db.WithNotifyTx(s, w, r, conn, 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 {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
} else {
|
||||
w.WriteHeader(http.StatusConflict)
|
||||
}
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user