forked from hnrss/hnrss
-
Notifications
You must be signed in to change notification settings - Fork 0
/
params.go
89 lines (76 loc) · 1.84 KB
/
params.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package main
import (
"fmt"
"net/url"
"strconv"
"strings"
)
const (
HitsPerPageLimit = 100
)
type OutputParams struct {
Title string
Link string
Description string `form:"description"`
LinkTo string `form:"link"`
Format string
SelfLink string
}
type SearchParams struct {
Tags string
Query string `form:"q"`
OptionalWords string
Filters string
Points string `form:"points"`
ID string `form:"id"`
Author string `form:"author"`
Comments string `form:"comments"`
SearchAttributes string `form:"search_attrs"`
Count string `form:"count"`
}
func (sp *SearchParams) numericFilters() string {
var filters []string
if sp.Points != "" {
filters = append(filters, "points>="+sp.Points)
}
if sp.Comments != "" {
filters = append(filters, "num_comments>="+sp.Comments)
}
return strings.Join(filters, ",")
}
// Encode transforms the search options into an Algolia search querystring
func (sp *SearchParams) Values() url.Values {
params := make(url.Values)
if sp.OptionalWords != "" {
params.Set("query", sp.Query)
params.Set("optionalWords", sp.OptionalWords)
} else if sp.Query != "" {
params.Set("query", fmt.Sprintf("\"%s\"", sp.Query))
}
if f := sp.numericFilters(); f != "" {
params.Set("numericFilters", f)
}
searchAttrs := sp.SearchAttributes
if searchAttrs == "" {
searchAttrs = "title"
}
if searchAttrs != "default" {
params.Set("restrictSearchableAttributes", searchAttrs)
}
if sp.Count != "" {
c, err := strconv.Atoi(sp.Count)
if err != nil {
c = 20
} else if c > HitsPerPageLimit {
c = HitsPerPageLimit
}
params.Set("hitsPerPage", strconv.Itoa(c))
}
if sp.Filters != "" {
params.Set("filters", sp.Filters)
}
if sp.Tags != "" {
params.Set("tags", sp.Tags)
}
return params
}