From a383129abbf3cac1c4ba93a6720b250b68358e81 Mon Sep 17 00:00:00 2001 From: Achim Rohn Date: Wed, 8 Apr 2026 14:50:45 +0200 Subject: [PATCH] Add utility methods for handling queue handler results and payload mapping --- mapping.go | 2 +- queue/general_queue.go | 60 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 1 deletion(-) diff --git a/mapping.go b/mapping.go index 3503703..eda8c8a 100644 --- a/mapping.go +++ b/mapping.go @@ -22,7 +22,7 @@ func StructToMap(data interface{}) (JSONB, error) { return result, nil } -func MapToStruct(data JSONB, result interface{}) error { +func MapToStruct(data JSONB, result any) error { // Marshal map to JSON bytes jsonBytes, err := json.Marshal(data) if err != nil { diff --git a/queue/general_queue.go b/queue/general_queue.go index 6aa6098..c83b089 100644 --- a/queue/general_queue.go +++ b/queue/general_queue.go @@ -33,11 +33,71 @@ type GeneralQueueJob struct { ResultPayload map[string]interface{} } +func (j GeneralQueueJob) LoadPayloadStruct(target any) error { + return MapToStruct(j.Payload, target) +} + type GeneralQueueHandlerResult struct { ResultPayload map[string]interface{} FailurePayload map[string]interface{} } +func NewSuccessGeneralQueueHandlerResult(result any) (GeneralQueueHandlerResult, error) { + resultMap, err := StructToMap(result) + if err != nil { + return returnStructToMapError(err), err + } + return GeneralQueueHandlerResult{ + ResultPayload: resultMap, + FailurePayload: nil, + }, nil +} + +const structToMapErrorKey = "structToMapError" + +func returnStructToMapError(err error) GeneralQueueHandlerResult { + return GeneralQueueHandlerResult{ + FailurePayload: map[string]interface{}{ + structToMapErrorKey: err.Error(), + }, + } +} + +func FailureGeneralQueueHandlerResult(message string, err error) GeneralQueueHandlerResult { + return GeneralQueueHandlerResult{ + FailurePayload: map[string]interface{}{ + "message": message, + "error": err.Error(), + }, + } +} + +func NewFailureGeneralQueueHandlerResult(failure any) (GeneralQueueHandlerResult, error) { + failureMap, err := StructToMap(failure) + if err != nil { + return returnStructToMapError(err), err + } + return GeneralQueueHandlerResult{ + ResultPayload: nil, + FailurePayload: failureMap, + }, nil +} + +func NewGeneralQueueHandlerResult(result any, failure any) (GeneralQueueHandlerResult, error) { + resultMap, err := StructToMap(result) + if err != nil { + return returnStructToMapError(err), err + } + failureMap, err := StructToMap(failure) + if err != nil { + return returnStructToMapError(err), err + } + return GeneralQueueHandlerResult{ + ResultPayload: resultMap, + FailurePayload: failureMap, + }, nil +} + type GeneralQueueHandler func(ctx context.Context, job GeneralQueueJob) (GeneralQueueHandlerResult, error) type GeneralQueueParams struct {