Last active
June 17, 2025 17:09
-
-
Save blinkinglight/774ff158e363771ece706dd0125d5f64 to your computer and use it in GitHub Desktop.
bee in action
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| router.Get("/stream/{id}", func(w http.ResponseWriter, r *http.Request) { | |
| w.WriteHeader(200) | |
| id := chi.URLParam(r, "id") | |
| sse := datastar.NewSSE(w, r) | |
| _ = sse | |
| ctx := bee.WithJetStream(r.Context(), js) | |
| ctx = bee.WithNats(ctx, nc) | |
| agg := &Aggregate{} | |
| updates := bee.ReplayAndSubscribe(ctx, users.Aggregate, id, agg) | |
| go func() { | |
| for { | |
| select { | |
| case <-r.Context().Done(): | |
| return | |
| case update := <-updates: | |
| sse.MergeFragmentTempl(partials.History(update.History)) | |
| } | |
| } | |
| }() | |
| <-r.Context().Done() | |
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| type userModel struct { | |
| Name string `json:"name"` | |
| Country string `json:"country"` | |
| } | |
| type Aggregate struct { | |
| History []string | |
| } | |
| func (a *Aggregate) ApplyEvent(event *gen.EventEnvelope) error { | |
| switch event.EventType { | |
| case "created": | |
| var user userModel | |
| if err := json.Unmarshal(event.Payload, &user); err != nil { | |
| return err | |
| } | |
| a.History = append(a.History, "User created: "+user.Name+" from "+user.Country) | |
| case "updated": | |
| var user userModel | |
| if err := json.Unmarshal(event.Payload, &user); err != nil { | |
| return err | |
| } | |
| a.History = append(a.History, "User updated: "+user.Name+" from "+user.Country) | |
| default: | |
| return nil // Ignore other event types | |
| } | |
| return nil | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment