Skip to content

Commit ae4e8b2

Browse files
committed
feat: added FieldError struct and modified NewFieldErrorsBodyData function
1 parent 83a7834 commit ae4e8b2

File tree

1 file changed

+39
-13
lines changed

1 file changed

+39
-13
lines changed

http/response/types.go

Lines changed: 39 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package response
22

33
import (
44
goflagsmode "github.com/ralvarezdev/go-flags/mode"
5-
gostringsconvert "github.com/ralvarezdev/go-strings/convert"
65
)
76

87
type (
@@ -20,6 +19,12 @@ type (
2019
Message *string `json:"message,omitempty"`
2120
Code *int `json:"code,omitempty"`
2221
}
22+
23+
// FieldError struct
24+
FieldError struct {
25+
Field string
26+
Err error
27+
}
2328
)
2429

2530
// NewJSendSuccessBody creates a new success response body
@@ -154,22 +159,43 @@ func NewErrorResponse(
154159
return NewDebugErrorResponse(err, err, data, errorCode, httpStatus)
155160
}
156161

157-
// NewFieldBodyData creates a new field body data
158-
func NewFieldBodyData(
159-
fieldName string,
160-
fieldValue ...interface{},
161-
) *map[string]interface{} {
162-
return &map[string]interface{}{
163-
fieldName: &[]interface{}{fieldValue},
162+
// NewFieldError creates a new field error
163+
func NewFieldError(
164+
field string,
165+
err error,
166+
) *FieldError {
167+
return &FieldError{
168+
Field: field,
169+
Err: err,
164170
}
165171
}
166172

167-
// NewFieldErrorsBodyData creates a new single field errors body data
173+
// NewFieldErrorsBodyData creates a new field errors body data
168174
func NewFieldErrorsBodyData(
169-
fieldName string,
170-
fieldValue ...error,
175+
fieldErrors ...FieldError,
171176
) *map[string]*[]string {
172-
return &map[string]*[]string{
173-
fieldName: gostringsconvert.ErrorArrayToStringArray(&fieldValue),
177+
// Check if there are field errors
178+
if len(fieldErrors) == 0 {
179+
return nil
174180
}
181+
182+
// Initialize the field errors map
183+
fieldErrorsMap := make(map[string]*[]string)
184+
185+
// Iterate over the field errors
186+
for _, fieldError := range fieldErrors {
187+
// Check if the field name exists in the map
188+
if _, ok := fieldErrorsMap[fieldError.Field]; !ok {
189+
// Initialize the field errors slice
190+
fieldErrorsMap[fieldError.Field] = &[]string{fieldError.Err.Error()}
191+
} else {
192+
// Append the error to the field errors slice
193+
*fieldErrorsMap[fieldError.Field] = append(
194+
*fieldErrorsMap[fieldError.Field],
195+
fieldError.Err.Error(),
196+
)
197+
}
198+
}
199+
200+
return &fieldErrorsMap
175201
}

0 commit comments

Comments
 (0)