|
| 1 | +package handler |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "log/slog" |
| 8 | + |
| 9 | + "github.com/OliverSchlueter/goutils/broker" |
| 10 | + "github.com/OliverSchlueter/goutils/middleware" |
| 11 | + "github.com/OliverSchlueter/goutils/problems" |
| 12 | + "github.com/OliverSchlueter/goutils/sloki" |
| 13 | + "github.com/fancyinnovations/fancyspaces/core/internal/spaces" |
| 14 | + spaces2 "github.com/fancyinnovations/fancyspaces/integrations/spaces-go-sdk/spaces" |
| 15 | + "github.com/nats-io/nats.go" |
| 16 | +) |
| 17 | + |
| 18 | +type NatsHandler struct { |
| 19 | + broker broker.Broker |
| 20 | + store *spaces.Store |
| 21 | +} |
| 22 | + |
| 23 | +type NatsConfiguration struct { |
| 24 | + Broker broker.Broker |
| 25 | + Store *spaces.Store |
| 26 | +} |
| 27 | + |
| 28 | +func NewNatsHandler(cfg NatsConfiguration) *NatsHandler { |
| 29 | + return &NatsHandler{ |
| 30 | + broker: cfg.Broker, |
| 31 | + store: cfg.Store, |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +func (h *NatsHandler) Register() error { |
| 36 | + if err := h.broker.SubscribeQueue("fancyspaces.core.spaces.get", "fancyspaces.core.spaces.get", middleware.NatsLogging(h.handleGet)); err != nil { |
| 37 | + return fmt.Errorf("could not subscribe to nats subject: %w", err) |
| 38 | + } |
| 39 | + |
| 40 | + return nil |
| 41 | +} |
| 42 | + |
| 43 | +func (h *NatsHandler) handleGet(msg *nats.Msg) { |
| 44 | + id := string(msg.Data) |
| 45 | + |
| 46 | + if id == "" { |
| 47 | + problems.ValidationError("space_id", "Space ID is required").WriteToBroker(h.broker, msg.Reply) |
| 48 | + return |
| 49 | + } |
| 50 | + |
| 51 | + space, err := h.store.GetByID(id) |
| 52 | + if err != nil { |
| 53 | + if errors.Is(err, spaces.ErrSpaceNotFound) { |
| 54 | + problems.NotFound("Space", id).WriteToBroker(h.broker, msg.Reply) |
| 55 | + return |
| 56 | + } |
| 57 | + slog.Error("Could not get space", sloki.WrapError(err)) |
| 58 | + problems.InternalServerError("").WriteToBroker(h.broker, msg.Reply) |
| 59 | + return |
| 60 | + } |
| 61 | + |
| 62 | + response, err := json.Marshal(spaces2.InternalSpace{ |
| 63 | + Space: *space, |
| 64 | + AnalyticsWriteKey: space.AnalyticsSettings.WriteKey, |
| 65 | + }) |
| 66 | + if err != nil { |
| 67 | + slog.Error("failed to marshal space", sloki.WrapError(err)) |
| 68 | + problems.InternalServerError("Could not marshal space").WriteToBroker(h.broker, msg.Reply) |
| 69 | + return |
| 70 | + } |
| 71 | + |
| 72 | + if err := h.broker.Publish(msg.Reply, response); err != nil { |
| 73 | + slog.Error("failed to publish space response", sloki.WrapError(err)) |
| 74 | + } |
| 75 | +} |
0 commit comments