forked from animenotifier/kitsu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
StreamMappings.go
50 lines (38 loc) · 908 Bytes
/
StreamMappings.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package kitsu
import (
"strings"
"time"
)
// StreamMappings returns a stream of all mappings (async).
func StreamMappings() chan *Mapping {
channel := make(chan *Mapping)
url := "mappings?page[limit]=20&page[offset]=0&include=item"
ticker := time.NewTicker(500 * time.Millisecond)
rateLimit := ticker.C
go func() {
defer close(channel)
defer ticker.Stop()
for {
page, err := GetMappingsPage(url)
if err != nil {
panic(err)
}
// Feed mapping data from current page to the stream
for _, mapping := range page.Data {
channel <- mapping
}
nextURL := page.Links.Next
// Did we reach the end?
if nextURL == "" {
break
}
// Cut off API base URL
nextURL = strings.TrimPrefix(nextURL, APIBaseURL)
// Continue with the next page
url = nextURL
// Wait for rate limiter to allow the next request
<-rateLimit
}
}()
return channel
}