relay_adapter.go raw

   1  //go:build !js && !wasm
   2  
   3  package marmot
   4  
   5  import (
   6  	"context"
   7  
   8  	"git.smesh.lol/orly/pkg/nostr/encoders/event"
   9  	"git.smesh.lol/orly/pkg/nostr/encoders/filter"
  10  	"git.smesh.lol/orly/pkg/nostr/ws"
  11  )
  12  
  13  // WSRelayAdapter wraps a ws.Client to satisfy the RelayConnection interface.
  14  type WSRelayAdapter struct {
  15  	client *ws.Client
  16  }
  17  
  18  // NewWSRelayAdapter creates a RelayConnection from an existing ws.Client.
  19  func NewWSRelayAdapter(c *ws.Client) *WSRelayAdapter {
  20  	return &WSRelayAdapter{client: c}
  21  }
  22  
  23  func (a *WSRelayAdapter) Publish(ctx context.Context, ev *event.E) error {
  24  	return a.client.Publish(ctx, ev)
  25  }
  26  
  27  func (a *WSRelayAdapter) Subscribe(ctx context.Context, ff *filter.S) (EventStream, error) {
  28  	sub, err := a.client.Subscribe(ctx, ff)
  29  	if err != nil {
  30  		return nil, err
  31  	}
  32  	return &wsEventStream{sub: sub}, nil
  33  }
  34  
  35  // wsEventStream wraps ws.Subscription to satisfy EventStream.
  36  type wsEventStream struct {
  37  	sub *ws.Subscription
  38  }
  39  
  40  func (s *wsEventStream) Events() <-chan *event.E { return s.sub.Events }
  41  func (s *wsEventStream) Close()                  { s.sub.Unsub() }
  42