bus.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package borealis
  2. import (
  3. "fmt"
  4. "github.com/nats-io/nats.go"
  5. )
  6. type Bus struct {
  7. NATS *nats.EncodedConn
  8. }
  9. type SubscriberHandler func(event *Event)
  10. func Connect(url string) (*Bus, error) {
  11. nats.RegisterEncoder("v1", &V1MessageEncoder{})
  12. conn, err := nats.Connect(url)
  13. if err != nil {
  14. return nil, fmt.Errorf("failed to connect to the broker: %w", err)
  15. }
  16. encodedConn, err := nats.NewEncodedConn(conn, "v1")
  17. if err != nil {
  18. return nil, fmt.Errorf("failed to configure the bus encoding: %w", err)
  19. }
  20. return &Bus{NATS: encodedConn}, nil
  21. }
  22. func (bus *Bus) SendEmail(request *SendEmail) error {
  23. return bus.Publish("email.outbound", request)
  24. }
  25. func (bus *Bus) RegisterID(request *RegisterID) error {
  26. return bus.Publish("id.register", request)
  27. }
  28. func (bus *Bus) VerifyEmail(request *VerifyEmail) error {
  29. return bus.Publish("id.verify", request)
  30. }
  31. func (bus *Bus) GrantAccess(request *GrantAccess) error {
  32. return bus.Publish("access.grant", request)
  33. }
  34. func (bus *Bus) RevokeAccess(request *RevokeAccess) error {
  35. return bus.Publish("access.revoke", request)
  36. }
  37. func (bus *Bus) Publish(stream string, request interface{}) error {
  38. rawEvent, err := NewRawEvent(0, request) // TODO
  39. if err != nil {
  40. return err
  41. }
  42. return bus.PublishRawEvent(stream, rawEvent)
  43. }
  44. func (bus *Bus) PublishRawEvent(stream string, rawEvent *RawEvent) error {
  45. if err := bus.NATS.Publish(stream, rawEvent); err != nil {
  46. return fmt.Errorf("failed to publish message: %w", err)
  47. }
  48. return nil
  49. }
  50. func (bus *Bus) Subscribe(stream string, handler SubscriberHandler) (*nats.Subscription, error) {
  51. return bus.NATS.Subscribe(stream, func(rawEvent RawEvent) {
  52. event, err := rawEvent.Check()
  53. if err == nil { // ignore invalid messages
  54. handler(event)
  55. }
  56. })
  57. }