natsio/stream.go

66 lines
1.5 KiB
Go
Raw Normal View History

2021-10-08 04:23:59 +00:00
package natsio
import (
"errors"
"fmt"
"github.com/nats-io/nats.go"
)
2021-10-08 04:40:59 +00:00
// GetStreamInfo ...
func GetStreamInfo(name string) (*nats.StreamInfo, error) {
return natsJS.StreamInfo(name)
}
2021-10-08 04:23:59 +00:00
// AddStream add new stream, with default config
func AddStream(name string, subjects []string) error {
// Get info about the stream
2021-10-08 05:00:03 +00:00
stream, _ := GetStreamInfo(name)
2021-10-08 04:23:59 +00:00
// If stream not found, create new
if stream == nil {
2021-10-08 04:33:32 +00:00
_, err := natsJS.AddStream(&nats.StreamConfig{
2021-10-08 04:23:59 +00:00
Name: name,
Subjects: subjects,
Storage: nats.FileStorage,
})
if err != nil {
msg := fmt.Sprintf("add stream error: %s", err.Error())
return errors.New(msg)
}
}
return nil
}
2021-10-08 05:00:03 +00:00
// DeleteStream ...
func DeleteStream(name string) error {
if err := natsJS.DeleteStream(name); err != nil {
msg := fmt.Sprintf("delete stream error: %s", err.Error())
return errors.New(msg)
}
return nil
}
// AddStreamSubjects ...
func AddStreamSubjects(name string, subjects []string) error {
// Get info about the stream
stream, _ := GetStreamInfo(name)
if stream == nil {
msg := fmt.Sprintf("error when adding stream %s subjects: stream not found", name)
return errors.New(msg)
}
// Merge current and new subjects
newSubjects := mergeAndUniqueArrayStrings(subjects, stream.Config.Subjects)
_, err := natsJS.UpdateStream(&nats.StreamConfig{
Name: name,
Subjects: newSubjects,
})
if err != nil {
msg := fmt.Sprintf("add stream error: %s", err.Error())
return errors.New(msg)
}
return nil
}