diff --git a/handler_utils/sqs.go b/handler_utils/sqs.go index fdc8a907de5211f3a6e5ef04d9300462428e8c3d..837ad9cf1ce56f83dfd9c56f409439b23f778367 100644 --- a/handler_utils/sqs.go +++ b/handler_utils/sqs.go @@ -1,9 +1,11 @@ package handler_utils import ( + "encoding/json" "github.com/aws/aws-lambda-go/events" "gitlab.com/uafrica/go-utils/errors" "gitlab.com/uafrica/go-utils/logs" + "reflect" ) // ValidateSQSEndpoints checks that all SQS endpoints are correctly defined using one of the supported handler types @@ -36,3 +38,23 @@ func ValidateSQSEndpoints(endpoints map[string]interface{}) (map[string]interfac logs.Info("Checked %d legacy and %d new handlers\n", countLegacy, countHandler) return endpoints, nil } + +func GetRecord(message events.SQSMessage, recordType reflect.Type) (interface{}, error) { + recordValuePtr := reflect.New(recordType) + err := json.Unmarshal([]byte(message.Body), recordValuePtr.Interface()) + if err != nil { + return nil, errors.Wrapf(err, "failed to JSON decode message body") + } + + if validator, ok := recordValuePtr.Interface().(IValidator); ok { + if err := validator.Validate(); err != nil { + return nil, errors.Wrapf(err, "invalid message body") + } + } + + return recordValuePtr.Elem().Interface(), nil +} + +type IValidator interface { + Validate() error +}