Compare commits

...

2 Commits

Author SHA1 Message Date
Hein
09a3dc92b9 fix(restheadspec): normalize empty results to objects instead of arrays 2026-05-18 14:37:46 +02:00
Hein
6590cd789a fix(nestedCUD): re-select rows after insert/update for accurate state
* Ensure result.Data reflects DB-generated defaults after insert.
* Update result.Data with current DB state after update.
2026-05-18 13:10:13 +02:00
3 changed files with 67 additions and 38 deletions

View File

@@ -125,6 +125,13 @@ func (p *NestedCUDProcessor) ProcessNestedCUD(
result.AffectedRows = 1 result.AffectedRows = 1
result.Data = regularData result.Data = regularData
// Re-select the inserted row so result.Data reflects DB-generated defaults.
if row, err := p.processSelect(ctx, tableName, id); err != nil {
logger.Warn("Select after insert failed: table=%s, id=%v, error=%v", tableName, id, err)
} else if len(row) > 0 {
result.Data = row
}
// Process child relations after parent insert (to get parent ID) // Process child relations after parent insert (to get parent ID)
if err := p.processChildRelations(ctx, "insert", id, relationFields, result.RelationData, modelType, parentIDs); err != nil { if err := p.processChildRelations(ctx, "insert", id, relationFields, result.RelationData, modelType, parentIDs); err != nil {
logger.Error("Failed to process child relations after insert: table=%s, parentID=%v, relations=%+v, error=%v", tableName, id, relationFields, err) logger.Error("Failed to process child relations after insert: table=%s, parentID=%v, relations=%+v, error=%v", tableName, id, relationFields, err)
@@ -146,9 +153,16 @@ func (p *NestedCUDProcessor) ProcessNestedCUD(
result.AffectedRows = rows result.AffectedRows = rows
result.Data = regularData result.Data = regularData
// Re-select the updated row so result.Data reflects current DB state.
if row, err := p.processSelect(ctx, tableName, result.ID); err != nil {
logger.Warn("Select after update failed: table=%s, id=%v, error=%v", tableName, result.ID, err)
} else if len(row) > 0 {
result.Data = row
}
// Process child relations for update // Process child relations for update
if err := p.processChildRelations(ctx, "update", data[pkName], relationFields, result.RelationData, modelType, parentIDs); err != nil { if err := p.processChildRelations(ctx, "update", data[pkName], relationFields, result.RelationData, modelType, parentIDs); err != nil {
logger.Error("Failed to process child relations after update: table=%s, parentID=%v, relations=%+v, error=%v", tableName, data[pkName], relationFields, err) logger.Error("Failed to process child relations after update: table=%s, parentID=%v, relations=%+v, error=%v", tableName, data[pkName], regularData, err)
return nil, fmt.Errorf("failed to process child relations: %w", err) return nil, fmt.Errorf("failed to process child relations: %w", err)
} }
} else { } else {
@@ -294,6 +308,20 @@ func (p *NestedCUDProcessor) processInsert(
return id, nil return id, nil
} }
// processSelect fetches the row identified by id from tableName into a flat map.
// Used to populate result.Data with the actual DB state after insert/update.
func (p *NestedCUDProcessor) processSelect(ctx context.Context, tableName string, id interface{}) (map[string]interface{}, error) {
pkName := reflection.GetPrimaryKeyName(tableName)
var row map[string]interface{}
if err := p.db.NewSelect().
Table(tableName).
Where(fmt.Sprintf("%s = ?", QuoteIdent(pkName)), id).
Scan(ctx, &row); err != nil {
return nil, fmt.Errorf("select after write failed: %w", err)
}
return row, nil
}
// processUpdate handles update operation // processUpdate handles update operation
func (p *NestedCUDProcessor) processUpdate( func (p *NestedCUDProcessor) processUpdate(
ctx context.Context, ctx context.Context,

View File

@@ -9,29 +9,29 @@ import (
"github.com/bitechdev/ResolveSpec/pkg/common" "github.com/bitechdev/ResolveSpec/pkg/common"
) )
// Test that normalizeResultArray returns empty array when no records found without ID // Test that normalizeResultArray returns empty object when no records found (single-record mode)
func TestNormalizeResultArray_EmptyArrayWhenNoID(t *testing.T) { func TestNormalizeResultArray_EmptyArrayWhenNoID(t *testing.T) {
handler := &Handler{} handler := &Handler{}
tests := []struct { tests := []struct {
name string name string
input interface{} input interface{}
shouldBeEmptyArr bool shouldBeEmptyObj bool
}{ }{
{ {
name: "nil should return empty array", name: "nil should return empty object",
input: nil, input: nil,
shouldBeEmptyArr: true, shouldBeEmptyObj: true,
}, },
{ {
name: "empty slice should return empty array", name: "empty slice should return empty object",
input: []*EmptyTestModel{}, input: []*EmptyTestModel{},
shouldBeEmptyArr: true, shouldBeEmptyObj: true,
}, },
{ {
name: "single element should return the element", name: "single element should return the element",
input: []*EmptyTestModel{{ID: 1, Name: "test"}}, input: []*EmptyTestModel{{ID: 1, Name: "test"}},
shouldBeEmptyArr: false, shouldBeEmptyObj: false,
}, },
{ {
name: "multiple elements should return the slice", name: "multiple elements should return the slice",
@@ -39,7 +39,7 @@ func TestNormalizeResultArray_EmptyArrayWhenNoID(t *testing.T) {
{ID: 1, Name: "test1"}, {ID: 1, Name: "test1"},
{ID: 2, Name: "test2"}, {ID: 2, Name: "test2"},
}, },
shouldBeEmptyArr: false, shouldBeEmptyObj: false,
}, },
} }
@@ -47,25 +47,25 @@ func TestNormalizeResultArray_EmptyArrayWhenNoID(t *testing.T) {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
result := handler.normalizeResultArray(tt.input) result := handler.normalizeResultArray(tt.input)
// For cases that should return empty array // For cases that should return empty object
if tt.shouldBeEmptyArr { if tt.shouldBeEmptyObj {
emptyArr, ok := result.([]interface{}) emptyObj, ok := result.(map[string]interface{})
if !ok { if !ok {
t.Errorf("Expected empty array []interface{}{}, got %T: %v", result, result) t.Errorf("Expected empty object map[string]interface{}{}, got %T: %v", result, result)
return return
} }
if len(emptyArr) != 0 { if len(emptyObj) != 0 {
t.Errorf("Expected empty array with length 0, got length %d", len(emptyArr)) t.Errorf("Expected empty object with length 0, got length %d", len(emptyObj))
} }
// Verify it serializes to [] and not null // Verify it serializes to {} and not null
jsonBytes, err := json.Marshal(result) jsonBytes, err := json.Marshal(result)
if err != nil { if err != nil {
t.Errorf("Failed to marshal result: %v", err) t.Errorf("Failed to marshal result: %v", err)
return return
} }
if string(jsonBytes) != "[]" { if string(jsonBytes) != "{}" {
t.Errorf("Expected JSON '[]', got '%s'", string(jsonBytes)) t.Errorf("Expected JSON '{}', got '%s'", string(jsonBytes))
} }
} }
}) })
@@ -138,12 +138,12 @@ func TestSendResponseWithOptions_NoDataFoundHeader(t *testing.T) {
t.Errorf("Expected X-No-Data-Found header to be 'true', got '%s'", mockWriter.headers["X-No-Data-Found"]) t.Errorf("Expected X-No-Data-Found header to be 'true', got '%s'", mockWriter.headers["X-No-Data-Found"])
} }
// Check status code is 200 // Check status code is 204 when no records found
if mockWriter.statusCode != 200 { if mockWriter.statusCode != 204 {
t.Errorf("Expected status code 200, got %d", mockWriter.statusCode) t.Errorf("Expected status code 204, got %d", mockWriter.statusCode)
} }
// Verify the body is an empty array // Verify the body is an empty array (list request, SingleRecordAsObject not set)
if mockWriter.body == nil { if mockWriter.body == nil {
t.Error("Expected body to be set, got nil") t.Error("Expected body to be set, got nil")
} else { } else {

View File

@@ -2502,14 +2502,16 @@ func (h *Handler) sendResponseWithOptions(w common.ResponseWriter, data interfac
w.SetHeader("X-No-Data-Found", "true") w.SetHeader("X-No-Data-Found", "true")
} }
w.WriteHeader(http.StatusOK)
// Normalize single-record arrays to objects if requested // Normalize single-record arrays to objects if requested
if options != nil && options.SingleRecordAsObject { if options != nil && options.SingleRecordAsObject {
data = h.normalizeResultArray(data) data = h.normalizeResultArray(data)
} }
// Return data as-is without wrapping in common.Response if dataLen == 0 {
w.WriteHeader(http.StatusNoContent)
} else {
w.WriteHeader(http.StatusOK)
}
if err := w.WriteJSON(data); err != nil { if err := w.WriteJSON(data); err != nil {
logger.Error("Failed to write JSON response: %v", err) logger.Error("Failed to write JSON response: %v", err)
@@ -2520,7 +2522,7 @@ func (h *Handler) sendResponseWithOptions(w common.ResponseWriter, data interfac
// Returns the single element if data is a slice/array with exactly one element, otherwise returns data unchanged // Returns the single element if data is a slice/array with exactly one element, otherwise returns data unchanged
func (h *Handler) normalizeResultArray(data interface{}) interface{} { func (h *Handler) normalizeResultArray(data interface{}) interface{} {
if data == nil { if data == nil {
return []interface{}{} return map[string]interface{}{}
} }
// Use reflection to check if data is a slice or array // Use reflection to check if data is a slice or array
@@ -2535,15 +2537,15 @@ func (h *Handler) normalizeResultArray(data interface{}) interface{} {
// Return the single element // Return the single element
return dataValue.Index(0).Interface() return dataValue.Index(0).Interface()
} else if dataValue.Len() == 0 { } else if dataValue.Len() == 0 {
// Keep empty array as empty array, don't convert to empty object // Single-record request with no result → empty object
return []interface{}{} return map[string]interface{}{}
} }
} }
if dataValue.Kind() == reflect.String { if dataValue.Kind() == reflect.String {
str := dataValue.String() str := dataValue.String()
if str == "" || str == "null" { if str == "" || str == "null" {
return []interface{}{} return map[string]interface{}{}
} }
} }
@@ -2552,9 +2554,6 @@ func (h *Handler) normalizeResultArray(data interface{}) interface{} {
// sendFormattedResponse sends response with formatting options // sendFormattedResponse sends response with formatting options
func (h *Handler) sendFormattedResponse(w common.ResponseWriter, data interface{}, metadata *common.Metadata, options ExtendedRequestOptions) { func (h *Handler) sendFormattedResponse(w common.ResponseWriter, data interface{}, metadata *common.Metadata, options ExtendedRequestOptions) {
// Normalize single-record arrays to objects if requested
httpStatus := http.StatusOK
// Handle nil data - convert to empty array // Handle nil data - convert to empty array
if data == nil { if data == nil {
data = []interface{}{} data = []interface{}{}
@@ -2566,8 +2565,10 @@ func (h *Handler) sendFormattedResponse(w common.ResponseWriter, data interface{
dataLen := reflection.Len(data) dataLen := reflection.Len(data)
// Add X-No-Data-Found header when no records were found // Add X-No-Data-Found header when no records were found
httpStatus := http.StatusOK
if dataLen == 0 { if dataLen == 0 {
w.SetHeader("X-No-Data-Found", "true") w.SetHeader("X-No-Data-Found", "true")
httpStatus = http.StatusNoContent
} }
// Apply normalization after header is set // Apply normalization after header is set