big ole refactor
This commit is contained in:
@@ -1,14 +1,23 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
"github.com/uptrace/bun"
|
||||
)
|
||||
|
||||
type AuditMeta struct {
|
||||
r *http.Request
|
||||
u *User
|
||||
}
|
||||
|
||||
func NewAudit(r *http.Request, u *User) *AuditMeta {
|
||||
if u == nil {
|
||||
u = CurrentUser(r.Context())
|
||||
}
|
||||
return &AuditMeta{r, u}
|
||||
}
|
||||
|
||||
// AuditInfo contains metadata for audit logging
|
||||
type AuditInfo struct {
|
||||
Action string // e.g., "seasons.create", "users.update"
|
||||
@@ -17,9 +26,6 @@ type AuditInfo struct {
|
||||
Details map[string]any // Changed fields or additional metadata
|
||||
}
|
||||
|
||||
// AuditCallback is called after successful database operations to log changes
|
||||
type AuditCallback func(ctx context.Context, tx bun.Tx, info *AuditInfo, r *http.Request) error
|
||||
|
||||
// extractTableName gets the bun table name from a model type using reflection
|
||||
// Example: Season with `bun:"table:seasons,alias:s"` returns "seasons"
|
||||
func extractTableName[T any]() string {
|
||||
@@ -27,7 +33,7 @@ func extractTableName[T any]() string {
|
||||
t := reflect.TypeOf(model)
|
||||
|
||||
// Handle pointer types
|
||||
if t.Kind() == reflect.Ptr {
|
||||
if t.Kind() == reflect.Pointer {
|
||||
t = t.Elem()
|
||||
}
|
||||
|
||||
@@ -38,11 +44,9 @@ func extractTableName[T any]() string {
|
||||
bunTag := field.Tag.Get("bun")
|
||||
if bunTag != "" {
|
||||
// Parse tag: "table:seasons,alias:s" -> "seasons"
|
||||
parts := strings.Split(bunTag, ",")
|
||||
for _, part := range parts {
|
||||
if strings.HasPrefix(part, "table:") {
|
||||
return strings.TrimPrefix(part, "table:")
|
||||
}
|
||||
for part := range strings.SplitSeq(bunTag, ",") {
|
||||
part, _ := strings.CutPrefix(part, "table:")
|
||||
return part
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -81,7 +85,7 @@ func extractPrimaryKey[T any](model *T) any {
|
||||
}
|
||||
|
||||
v := reflect.ValueOf(model)
|
||||
if v.Kind() == reflect.Ptr {
|
||||
if v.Kind() == reflect.Pointer {
|
||||
v = v.Elem()
|
||||
}
|
||||
|
||||
@@ -110,7 +114,7 @@ func extractChangedFields[T any](model *T, columns []string) map[string]any {
|
||||
|
||||
result := make(map[string]any)
|
||||
v := reflect.ValueOf(model)
|
||||
if v.Kind() == reflect.Ptr {
|
||||
if v.Kind() == reflect.Pointer {
|
||||
v = v.Elem()
|
||||
}
|
||||
|
||||
@@ -142,5 +146,3 @@ func extractChangedFields[T any](model *T, columns []string) map[string]any {
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// Note: We don't need getTxFromQuery since we store the tx directly in our helper structs
|
||||
|
||||
Reference in New Issue
Block a user