-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
42 lines (37 loc) · 1.12 KB
/
service.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
package trivia
import "trivapi/db"
// Temporary solution - todo: cache properly
var cachedResults []triviaModel
// RandomTrivia - Get random trivia questions
func RandomTrivia(options db.QueryOptions) []triviaModel {
cachedTrivia := getCachedTrivia()
shuffledResults := Shuffle(cachedTrivia)
filterFunction := getFilterFunction(options.GetFilters())
filteredResults := Filter(filterFunction, shuffledResults)
return LimitArray(filteredResults, options.Amount)
}
func getCachedTrivia() []triviaModel {
if cachedResults == nil {
session := db.NewSession()
defer session.Close()
model := []triviaModel{}
col := session.Collection(collectionName, model)
results, _ := col.All()
cachedResults = results.([]triviaModel)
}
return cachedResults
}
func getFilterFunction(filters map[string]string) filterFunc {
cat := filters[categoryFilter]
diff := filters[difficultyFilter]
return func(t triviaModel) bool {
if cat != "" && diff != "" {
return t.Category == cat && t.Difficulty == diff
} else if cat != "" {
return t.Category == cat
} else if diff != "" {
return t.Difficulty == diff
}
return true
}
}