subscription.go

 1package resolvers
 2
 3import (
 4	"context"
 5	"fmt"
 6
 7	"github.com/git-bug/git-bug/api/graphql/graph"
 8	"github.com/git-bug/git-bug/api/graphql/models"
 9	"github.com/git-bug/git-bug/cache"
10	"github.com/git-bug/git-bug/entities/bug"
11	"github.com/git-bug/git-bug/entity"
12)
13
14var _ graph.SubscriptionResolver = &subscriptionResolver{}
15
16type subscriptionResolver struct {
17	cache *cache.MultiRepoCache
18}
19
20func (s subscriptionResolver) BugChanged(ctx context.Context, repoRef *string, query *string) (<-chan *models.BugChange, error) {
21	var repo *cache.RepoCache
22	var err error
23
24	if repoRef == nil {
25		repo, err = s.cache.DefaultRepo()
26	} else {
27		repo, err = s.cache.ResolveRepo(*repoRef)
28	}
29
30	if err != nil {
31		return nil, err
32	}
33
34	out := make(chan *models.BugChange)
35	sub := bugSubscription{out: out, repo: repo}
36	repo.RegisterObserver(bug.Typename, sub)
37
38	go func() {
39		<-ctx.Done()
40		repo.RegisterObserver(bug.Typename, sub)
41	}()
42
43	return out, nil
44}
45
46type bugSubscription struct {
47	out  chan *models.BugChange
48	repo *cache.RepoCache
49}
50
51func (bs bugSubscription) EntityCreated(_ string, id entity.Id) {
52	excerpt, err := bs.repo.Bugs().ResolveExcerpt(id)
53	if err != nil {
54		// Should never happen
55		fmt.Printf("bug in the cache: could not resolve excerpt for %s: %s\n", id, err)
56		return
57	}
58	bs.out <- &models.BugChange{
59		Type: models.ChangeTypeCreated,
60		Bug:  models.NewLazyBug(bs.repo, excerpt),
61	}
62}
63
64func (bs bugSubscription) EntityUpdated(_ string, id entity.Id) {
65	excerpt, err := bs.repo.Bugs().ResolveExcerpt(id)
66	if err != nil {
67		// Should never happen
68		fmt.Printf("bug in the cache: could not resolve excerpt for %s: %s\n", id, err)
69		return
70	}
71	bs.out <- &models.BugChange{
72		Type: models.ChangeTypeUpdated,
73		Bug:  models.NewLazyBug(bs.repo, excerpt),
74	}
75}