From 6b501d93255c6dc52dfe3ffef2d7ec2e12933b48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?France=CC=81=20Wilke?= <francewilke@gmail.com> Date: Fri, 10 Dec 2021 13:05:29 +0200 Subject: [PATCH] Add shared GetRecord --- handler_utils/sqs.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/handler_utils/sqs.go b/handler_utils/sqs.go index fdc8a90..837ad9c 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 +} -- GitLab