pocketbase/tools/subscriptions/broker.go

61 lines
1.5 KiB
Go
Raw Normal View History

2022-07-07 05:19:05 +08:00
package subscriptions
import (
"fmt"
2024-09-30 00:23:19 +08:00
"github.com/pocketbase/pocketbase/tools/list"
"github.com/pocketbase/pocketbase/tools/store"
2022-07-07 05:19:05 +08:00
)
// Broker defines a struct for managing subscriptions clients.
type Broker struct {
2024-09-30 00:23:19 +08:00
store *store.Store[Client]
2022-07-07 05:19:05 +08:00
}
// NewBroker initializes and returns a new Broker instance.
func NewBroker() *Broker {
return &Broker{
2024-09-30 00:23:19 +08:00
store: store.New[Client](nil),
2022-07-07 05:19:05 +08:00
}
}
// Clients returns a shallow copy of all registered clients indexed
// with their connection id.
2022-07-07 05:19:05 +08:00
func (b *Broker) Clients() map[string]Client {
2024-09-30 00:23:19 +08:00
return b.store.GetAll()
}
2024-09-30 00:23:19 +08:00
// ChunkedClients splits the current clients into a chunked slice.
func (b *Broker) ChunkedClients(chunkSize int) [][]Client {
return list.ToChunks(b.store.Values(), chunkSize)
2022-07-07 05:19:05 +08:00
}
// ClientById finds a registered client by its id.
//
// Returns non-nil error when client with clientId is not registered.
func (b *Broker) ClientById(clientId string) (Client, error) {
2024-09-30 00:23:19 +08:00
client, ok := b.store.GetOk(clientId)
2022-07-07 05:19:05 +08:00
if !ok {
2024-09-30 00:23:19 +08:00
return nil, fmt.Errorf("no client associated with connection ID %q", clientId)
2022-07-07 05:19:05 +08:00
}
return client, nil
}
// Register adds a new client to the broker instance.
func (b *Broker) Register(client Client) {
2024-09-30 00:23:19 +08:00
b.store.Set(client.Id(), client)
2022-07-07 05:19:05 +08:00
}
// Unregister removes a single client by its id.
//
// If client with clientId doesn't exist, this method does nothing.
func (b *Broker) Unregister(clientId string) {
2024-09-30 00:23:19 +08:00
client := b.store.Get(clientId)
if client == nil {
return
}
2024-09-30 00:23:19 +08:00
client.Discard()
b.store.Remove(clientId)
2022-07-07 05:19:05 +08:00
}