summaryrefslogtreecommitdiff
blob: 20da6fed7ba0617b57693da0c9358afc57c0640b (plain)
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
// Used to create package suggestions

package packages

import (
	"encoding/json"
	"github.com/go-pg/pg"
	"net/http"
	"soko/pkg/database"
	"soko/pkg/models"
)

// Suggest returns json encoded suggestions of
// packages based on the given query
func Suggest(w http.ResponseWriter, r *http.Request) {

	searchTerm := getParameterValue("q", r)
	searchQuery := buildSearchQuery(searchTerm)

	var packages []models.Package
	err := database.DBCon.Model(&packages).
		Where(searchQuery).
		Relation("Versions").
		Select()
	if err != nil && err != pg.ErrNoRows {
		http.Error(w, http.StatusText(http.StatusInternalServerError),
			http.StatusInternalServerError)
		return
	}

	type Result struct {
		Name        string `json:"name"`
		Category    string `json:"category"`
		description string `json:"description"`
	}

	type Results struct {
		Results []*Result `json:"results"`
	}

	var results []*Result

	for _, gpackage := range packages {
		results = append(results, &Result{
			Name:        gpackage.Name,
			Category:    gpackage.Category,
			description: gpackage.Versions[0].Description,
		})
	}

	result := Results{
		Results: results,
	}

	b, err := json.Marshal(result)

	if err != nil {
		http.Error(w, http.StatusText(http.StatusInternalServerError),
			http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.Write(b)
}