Skip to content
Snippets Groups Projects
Select Git revision
  • main default protected
  • trading_hours
  • refactor_trading_hours
  • audit_cleaning_cater_for_non_struct_fields
  • remove-info-logs
  • sl-refactor
  • 18-use-scan-for-param-values
  • 17-order-search-results
  • 4-simplify-framework-2
  • 1-http-error
  • v1.294.0
  • v1.293.0
  • v1.292.0
  • v1.291.0
  • v1.290.0
  • v1.289.0
  • v1.288.0
  • v1.287.0
  • v1.286.0
  • v1.285.0
  • v1.284.0
  • v1.283.0
  • v1.282.0
  • v1.281.0
  • v1.280.0
  • v1.279.0
  • v1.278.0
  • v1.277.0
  • v1.276.0
  • v1.275.0
30 results

sqs.go

Blame
  • sqs.go 1.86 KiB
    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
    // return updated endpoints with additional information
    func ValidateSQSEndpoints(endpoints map[string]interface{}) (map[string]interface{}, error) {
    	countLegacy := 0
    	countHandler := 0
    	for messageType, handlerFunc := range endpoints {
    		if messageType == "" {
    			return nil, errors.Errorf("blank messageType")
    		}
    		if handlerFunc == nil {
    			return nil, errors.Errorf("nil handler on %s", messageType)
    		}
    
    		if _, ok := handlerFunc.(func(req events.SQSEvent) (err error)); ok {
    			// ok - leave as is - we support this legacyHandler
    			countLegacy++
    		} else {
    			handler, err := NewSQSHandler(handlerFunc)
    			if err != nil {
    				return nil, errors.Wrapf(err, "%v has invalid handler %T", messageType, handlerFunc)
    			}
    			// replace the endpoint value so we can quickly call this handler
    			endpoints[messageType] = handler
    			logs.Info("%s: OK (request: %v)\n", messageType, handler.RecordType)
    			countHandler++
    		}
    	}
    	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
    }