2024-08-21 10:04:09 +02:00
package tools
import (
"encoding/json"
"strings"
2024-09-04 10:53:12 +02:00
"cloud.o-forge.io/core/oc-lib/config"
2024-08-21 10:04:09 +02:00
"github.com/nats-io/nats.go"
)
2024-08-30 14:50:48 +02:00
// NATS Method Enum defines the different methods that can be used to interact with the NATS server
2024-08-21 10:04:09 +02:00
type NATSMethod int
const (
REMOVE NATSMethod = iota
CREATE
)
2024-08-30 14:50:48 +02:00
// NameToMethod returns the NATSMethod enum value from a string
2024-08-21 10:04:09 +02:00
func NameToMethod ( name string ) NATSMethod {
for _ , v := range [ ... ] NATSMethod { REMOVE , CREATE } {
if strings . Contains ( strings . ToLower ( v . String ( ) ) , strings . ToLower ( name ) ) {
return v
}
}
return - 1
}
2024-08-30 14:50:48 +02:00
// GenerateKey generates a key for the NATSMethod usefull for standard key based on data name & method
2024-08-21 10:04:09 +02:00
func ( d NATSMethod ) GenerateKey ( name string ) string {
return name + "_" + d . String ( )
}
2024-08-30 14:50:48 +02:00
// String returns the string of the enum
2024-08-21 10:04:09 +02:00
func ( d NATSMethod ) String ( ) string {
2024-08-22 15:04:01 +02:00
return [ ... ] string { "remove" , "create" , "discovery" } [ d ]
2024-08-21 10:04:09 +02:00
}
2024-08-21 10:21:17 +02:00
type natsCaller struct { }
2024-08-21 10:04:09 +02:00
2024-08-30 14:50:48 +02:00
// NewNATSCaller creates a new instance of the NATS Caller
2024-08-21 10:21:17 +02:00
func NewNATSCaller ( ) * natsCaller {
return & natsCaller { }
2024-08-21 10:04:09 +02:00
}
2024-08-30 14:50:48 +02:00
// SetNATSPub sets a message to the NATS server
2024-08-21 10:21:17 +02:00
func ( o * natsCaller ) SetNATSPub ( dataName string , method NATSMethod , data interface { } ) string {
2024-09-04 10:53:12 +02:00
if config . GetConfig ( ) . NATSUrl == "" {
2024-08-21 10:04:09 +02:00
return " -> NATS_SERVER is not set"
}
2024-09-04 10:53:12 +02:00
nc , err := nats . Connect ( config . GetConfig ( ) . NATSUrl )
2024-08-21 10:04:09 +02:00
if err != nil {
return " -> Could not reach NATS server : " + err . Error ( )
}
defer nc . Close ( )
js , err := json . Marshal ( data )
if err != nil {
return " -> " + err . Error ( )
}
2024-08-30 14:50:48 +02:00
err = nc . Publish ( method . GenerateKey ( dataName ) , js ) // Publish the message on the NATS server with a channel name based on the data name (or whatever start) and the method
2024-08-21 10:04:09 +02:00
if err != nil {
2024-08-30 14:50:48 +02:00
return " -> " + err . Error ( ) // Return an error if the message could not be published
2024-08-21 10:04:09 +02:00
}
return ""
}