79 lines
1.7 KiB
Go
79 lines
1.7 KiB
Go
package usecasehelper
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
|
|
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()
|
|
}
|
|
|
|
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)
|
|
}
|
|
|
|
func GetMiddlewareErrorCode(mwType MWType) string {
|
|
if strings.Contains(string(mwType), "Pre") {
|
|
return "MW_PRE_FAILED"
|
|
}
|
|
return "MW_POST_FAILED"
|
|
}
|
|
|
|
// GetLogData returns whichever of data or input is non-nil (prefers data)
|
|
func GetLogData(input interface{}, data interface{}) interface{} {
|
|
if data != nil {
|
|
return data
|
|
}
|
|
return input
|
|
}
|
|
|
|
func HandleMiddlewareError(event *pl.Event, mwType, mwName string, logData interface{}, err error) error {
|
|
event.Status = "failed"
|
|
event.ErrInfo = pl.ErrorInfo{
|
|
Code: GetMiddlewareErrorCode(MWType(mwType)),
|
|
Detail: fmt.Sprintf("%s middleware %s failed", mwType, mwName),
|
|
Raw: err,
|
|
}
|
|
return pl.SetLogError(event, logData)
|
|
}
|