github.com/wfusion/gofusion@v1.1.14/common/infra/watermill/components/requestreply/backend_pubsub_marshaler.go (about)

     1  package requestreply
     2  
     3  import (
     4  	"github.com/pkg/errors"
     5  
     6  	"github.com/wfusion/gofusion/common/infra/watermill/message"
     7  	"github.com/wfusion/gofusion/common/utils"
     8  	"github.com/wfusion/gofusion/common/utils/serialize/json"
     9  )
    10  
    11  type BackendPubsubMarshaler[Result any] interface {
    12  	MarshalReply(params BackendOnCommandProcessedParams[Result]) (*message.Message, error)
    13  	UnmarshalReply(msg *message.Message) (reply Reply[Result], err error)
    14  }
    15  
    16  const (
    17  	ErrorMetadataKey    = "_watermill_requestreply_error"
    18  	HasErrorMetadataKey = "_watermill_requestreply_has_error"
    19  )
    20  
    21  type BackendPubsubJSONMarshaler[Result any] struct{}
    22  
    23  func (m BackendPubsubJSONMarshaler[Result]) MarshalReply(
    24  	params BackendOnCommandProcessedParams[Result],
    25  ) (*message.Message, error) {
    26  	msg := message.NewMessage(utils.UUID(), nil)
    27  
    28  	if params.HandleErr != nil {
    29  		msg.Metadata.Set(ErrorMetadataKey, params.HandleErr.Error())
    30  		msg.Metadata.Set(HasErrorMetadataKey, "1")
    31  	} else {
    32  		msg.Metadata.Set(HasErrorMetadataKey, "0")
    33  	}
    34  
    35  	b, err := json.Marshal(params.HandlerResult)
    36  	if err != nil {
    37  		return nil, errors.Wrap(err, "cannot marshal reply")
    38  	}
    39  	msg.Payload = b
    40  
    41  	return msg, nil
    42  }
    43  
    44  func (m BackendPubsubJSONMarshaler[Result]) UnmarshalReply(msg *message.Message) (Reply[Result], error) {
    45  	reply := Reply[Result]{}
    46  
    47  	if msg.Metadata.Get(HasErrorMetadataKey) == "1" {
    48  		reply.Error = errors.New(msg.Metadata.Get(ErrorMetadataKey))
    49  	}
    50  
    51  	var result Result
    52  	if err := json.Unmarshal(msg.Payload, &result); err != nil {
    53  		return Reply[Result]{}, errors.Wrap(err, "cannot unmarshal result")
    54  	}
    55  	reply.HandlerResult = result
    56  
    57  	return reply, nil
    58  }