package main
import (
"context"
"fmt"
"time"
"github.com/go-mizu/mizu/view/sync"
)
type Todo struct {
ID string `json:"id"`
Title string `json:"title"`
Completed bool `json:"completed"`
CreatedAt time.Time `json:"created_at"`
}
func main() {
// Create client and collection
client := sync.New(sync.Options{
BaseURL: "http://localhost:8080/_sync",
Scope: "user:demo",
})
todos := sync.NewCollection[Todo](client, "todo")
// Start sync
ctx := context.Background()
client.Start(ctx)
// Reactive stats
stats := sync.NewComputed(func() string {
all := todos.All()
completed := 0
for _, e := range all {
if e.Get().Completed {
completed++
}
}
return fmt.Sprintf("%d/%d completed", completed, len(all))
})
// Log changes
sync.NewEffect(func() {
fmt.Println("Stats:", stats.Get())
})
// Create todos
todos.Create("1", Todo{Title: "Learn Go", CreatedAt: time.Now()})
todos.Create("2", Todo{Title: "Build app", CreatedAt: time.Now()})
todos.Create("3", Todo{Title: "Deploy", CreatedAt: time.Now()})
// Complete one
entity := todos.Get("1")
todo := entity.Get()
todo.Completed = true
entity.Set(todo)
// Find incomplete
incomplete := todos.Find(func(t Todo) bool { return !t.Completed })
fmt.Printf("\nIncomplete todos:\n")
for _, e := range incomplete {
fmt.Printf("- %s\n", e.Get().Title)
}
// Delete one
todos.Get("3").Delete()
// Keep running...
select {}
}