forked from algolia/algoliasearch-client-go
/
synonym_iterator.go
65 lines (56 loc) · 1.54 KB
/
synonym_iterator.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package algoliasearch
// SynonymIterator is the exposed structure to iterate over all the synonyms of
// an index.
type SynonymIterator struct {
index Index
synonyms []Synonym
hitsPerPage int
page int
pos int
}
// NewSynonymIterator returns a new SynonymIterator that will iterate over all
// the synonyms of the declared index.
func NewSynonymIterator(index Index) *SynonymIterator {
return &SynonymIterator{
index: index,
synonyms: nil,
hitsPerPage: 1000,
page: -1,
pos: -1,
}
}
// Next returns iterate to the next synonym of the underlying index. Every call
// to Next should yield a different synonym with a nil error until the
// algoliasearch.NoMoreSynonymsErr is returned which means that all the
// synonyms have been retrieved. If the error is of a different type, it means
// that the iteration could not have been done correctly.
func (it *SynonymIterator) Next() (*Synonym, error) {
if it.synonyms == nil || it.pos >= len(it.synonyms) {
if err := it.loadNextPage(); err != nil {
it.reset()
return nil, err
}
}
it.pos++
if it.pos >= len(it.synonyms) {
return nil, NoMoreSynonymsErr
}
synonym := it.synonyms[it.pos]
synonym.HighlightResult = nil
return &synonym, nil
}
func (it *SynonymIterator) loadNextPage() error {
it.pos = -1
it.page++
synonyms, err := it.index.SearchSynonyms("", nil, it.page, it.hitsPerPage)
if err != nil {
return err
}
it.synonyms = synonyms
return nil
}
func (it *SynonymIterator) reset() {
it.synonyms = nil
it.page = -1
it.pos = 0
}