feat(handler): implement default sort configuration for models

* Add SetDefaultSort method to configure default sort order
* Implement getDefaultSort method to retrieve configured defaults
* Update handleRead to apply default sort when none specified
* Add tests for default sort functionality
This commit is contained in:
Hein
2026-07-29 10:05:24 +02:00
parent a70e3e02d0
commit 7c737afc5a
6 changed files with 203 additions and 0 deletions
+32
View File
@@ -30,6 +30,7 @@ type Handler struct {
hooks *HookRegistry
fallbackHandler FallbackHandler
openAPIGenerator func() (string, error)
defaultSort map[string][]common.SortOption
}
// NewHandler creates a new API handler with database and registry abstractions
@@ -56,6 +57,32 @@ func (h *Handler) SetFallbackHandler(fallback FallbackHandler) {
h.fallbackHandler = fallback
}
// SetDefaultSort sets the sort order applied to list ("read") results when a
// request does not specify its own sort. Pass an empty schema and name to set
// a global default used by any model without a more specific default.
func (h *Handler) SetDefaultSort(schema, name string, sort ...common.SortOption) {
if h.defaultSort == nil {
h.defaultSort = make(map[string][]common.SortOption)
}
h.defaultSort[defaultSortKey(schema, name)] = sort
}
// getDefaultSort returns the configured default sort for a model, falling
// back to the global default (registered with an empty schema and name).
func (h *Handler) getDefaultSort(schema, name string) []common.SortOption {
if h.defaultSort == nil {
return nil
}
if sort, ok := h.defaultSort[defaultSortKey(schema, name)]; ok {
return sort
}
return h.defaultSort[defaultSortKey("", "")]
}
func defaultSortKey(schema, name string) string {
return fmt.Sprintf("%s.%s", schema, name)
}
// GetDatabase returns the underlying database connection
// Implements common.SpecHandler interface
func (h *Handler) GetDatabase() common.Database {
@@ -345,6 +372,11 @@ func (h *Handler) handleRead(ctx context.Context, w common.ResponseWriter, id st
query = query.Where(customOp.SQL)
}
// Fall back to the configured default sort when the request didn't specify one
if len(options.Sort) == 0 {
options.Sort = common.ResolveSortColumns(h.getDefaultSort(schema, entity), reflection.GetPrimaryKeyName(model))
}
// Apply sorting
for _, sort := range options.Sort {
direction := "ASC"