refactor use case
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
package usecasehelper
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
pl "simrs-vx/pkg/logger"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func SafeToResponse[T any](data *T) any {
|
||||
if data == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Use type assertion to call ToResponse if the type has it
|
||||
if converter, ok := any(data).(interface{ ToResponse() any }); ok {
|
||||
return converter.ToResponse()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func HandleReadError(err error, event *pl.Event, itemType string, id interface{}, data any) error {
|
||||
if err == nil {
|
||||
pl.SetLogInfo(event, data, "complete")
|
||||
return nil
|
||||
}
|
||||
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
event.Status = "failed"
|
||||
event.ErrInfo = pl.ErrorInfo{
|
||||
Code: "data-notFound",
|
||||
Detail: fmt.Sprintf("%s with ID %v not found", itemType, id),
|
||||
Raw: err,
|
||||
}
|
||||
} else {
|
||||
event.Status = "failed"
|
||||
event.ErrInfo = pl.ErrorInfo{
|
||||
Code: "data-read-detail-fail",
|
||||
Detail: fmt.Sprintf("%s read failed", itemType),
|
||||
Raw: err,
|
||||
}
|
||||
}
|
||||
|
||||
return pl.SetLogError(*event, nil)
|
||||
}
|
||||
Reference in New Issue
Block a user