55 lines
880 B
Go
55 lines
880 B
Go
package resolvers
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"log"
|
|
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
// This file will not be regenerated automatically.
|
|
//
|
|
// It serves as dependency injection for your app, add any dependencies you require here.
|
|
|
|
type Resolver struct {
|
|
Redis *redis.Client
|
|
}
|
|
|
|
func Subscribe[T any](ctx context.Context, redis *redis.Client, event string) (<-chan *T, error) {
|
|
|
|
clientChannel := make(chan *T, 1)
|
|
|
|
go func() {
|
|
sub := redis.Subscribe(ctx, event)
|
|
|
|
if _, err := sub.Receive(ctx); err != nil {
|
|
return
|
|
}
|
|
|
|
serverChannel := sub.Channel()
|
|
|
|
for {
|
|
select {
|
|
case message := <-serverChannel:
|
|
|
|
var obj *T
|
|
if err := json.Unmarshal([]byte(message.Payload), &obj); err != nil {
|
|
log.Print(err)
|
|
return
|
|
}
|
|
clientChannel <- obj
|
|
|
|
case <-ctx.Done():
|
|
|
|
sub.Close()
|
|
return
|
|
}
|
|
|
|
}
|
|
}()
|
|
|
|
return clientChannel, nil
|
|
|
|
}
|