diff --git a/pkg/events/nats/nats_producer.go b/pkg/events/nats/nats_producer.go index f32561f5..f2c4f76d 100644 --- a/pkg/events/nats/nats_producer.go +++ b/pkg/events/nats/nats_producer.go @@ -5,6 +5,7 @@ import ( logger_wrapper "github.com/evolution-foundation/evolution-go/pkg/logger" "github.com/gomessguii/logger" "github.com/nats-io/nats.go" + "strings" ) type natsProducer struct { @@ -20,6 +21,15 @@ func NewNatsProducer( natsGlobalEvents []string, loggerWrapper *logger_wrapper.LoggerManager, ) producer_interfaces.Producer { + if strings.TrimSpace(url) == "" { + return &natsProducer{ + conn: nil, + natsGlobalEnabled: false, + natsGlobalEvents: nil, + loggerWrapper: loggerWrapper, + } + } + conn, err := nats.Connect(url) if err != nil { logger.LogError("Failed to connect to NATS: %v", err) diff --git a/pkg/events/nats/nats_producer_test.go b/pkg/events/nats/nats_producer_test.go new file mode 100644 index 00000000..272fd682 --- /dev/null +++ b/pkg/events/nats/nats_producer_test.go @@ -0,0 +1,31 @@ +package nats_producer + +import "testing" + +func TestNewNatsProducerDoesNotConnectWithoutURL(t *testing.T) { + tests := []struct { + name string + url string + }{ + {"Empty URL", ""}, + {"Whitespace URL", " "}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + producer, ok := NewNatsProducer(tt.url, true, []string{"event1"}, nil).(*natsProducer) + if !ok { + t.Fatal("constructor returned an unexpected producer type") + } + if producer.conn != nil { + t.Fatal("NATS connection must stay nil when NATS_URL is empty") + } + if producer.natsGlobalEnabled { + t.Fatal("NATS global publishing must stay disabled without a URL") + } + if producer.natsGlobalEvents != nil { + t.Fatal("natsGlobalEvents must be nil when NATS_URL is empty") + } + }) + } +}