Browse Source

Implement PubSub.Topics

Volodymyr Tkach 2 years ago
parent
commit
904f0aba68
2 changed files with 33 additions and 0 deletions
  1. 15 0
      pubsub/pubsub.go
  2. 18 0
      pubsub/pubsub_test.go

+ 15 - 0
pubsub/pubsub.go

@@ -144,6 +144,21 @@ func (p *PubSub) Unlisten(topic string, params ...interface{}) {
 	}
 }
 
+// Topics returns all current listen topics.
+func (p *PubSub) Topics() []string {
+	p.Lock()
+	defer p.Unlock()
+
+	topics := []string{}
+	for _, c := range p.Connections {
+		for topic := range c.topics {
+			topics = append(topics, topic)
+		}
+	}
+
+	return topics
+}
+
 // HasTopic returns true if topic present.
 func (p *PubSub) HasTopic(topic string, params ...interface{}) bool {
 	p.Lock()

+ 18 - 0
pubsub/pubsub_test.go

@@ -71,6 +71,24 @@ var _ = Describe("PubSub", func() {
 			})
 		})
 
+		Context("Topics", func() {
+			It("return topics", func() {
+				Expect(len(ps.Connections)).To(Equal(0))
+
+				for i := 1; i <= 50; i++ {
+					ps.Listen("community-points-channel-v1", 1, i)
+				}
+				Expect(len(ps.Connections)).To(Equal(1))
+
+				ps.Listen("community-points-channel-v1", 2, 1)
+				Expect(len(ps.Connections)).To(Equal(2))
+
+				Expect(ps.Topics()).To(ContainElements(
+					"community-points-channel-v1.2.1",
+				))
+			})
+		})
+
 		Context("HasTopic", func() {
 			It("checks topics", func() {
 				Expect(len(ps.Connections)).To(Equal(0))