/
search.go
64 lines (57 loc) · 1.4 KB
/
search.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
package controllers
import (
"fmt"
"net/http"
e "github.com/chances/party-server/errors"
"github.com/chances/party-server/models"
s "github.com/chances/party-server/spotify"
"github.com/gin-gonic/gin"
"github.com/zmb3/spotify"
)
// Search controller
type Search struct {
Controller
}
// NewSearch creates a new Search controller
func NewSearch() Search {
newSearch := Search{}
newSearch.Setup()
return newSearch
}
// SearchTracks searches for Spotify tracks given a query string
func (cr *Search) SearchTracks() gin.HandlerFunc {
return func(c *gin.Context) {
query, exists := c.GetQuery("q")
if !exists {
query, exists = c.GetQuery("query")
}
if !exists {
c.Error(e.BadRequest.WithDetail("Malformed search, missing query"))
c.Abort()
return
}
spotifyClient, err := s.DefaultClient(cr.SpotifyDefaultAuth, cr.SpotifyAuth)
if err != nil {
c.Error(e.Internal.CausedBy(err))
c.Abort()
return
}
result, err := spotifyClient.Search(query, spotify.SearchTypeTrack)
if err != nil {
c.Error(e.Internal.CausedBy(err))
c.Abort()
return
}
c.JSON(http.StatusOK, models.NewResponse(
fmt.Sprintf("\"%s\":%d-%d", query, result.Tracks.Offset, result.Tracks.Total),
"search-tracks",
cr.RequestURI(c),
gin.H{
"tracks": result.Tracks.Tracks,
"limit": result.Tracks.Limit,
"offset": result.Tracks.Offset,
"total": result.Tracks.Total,
},
))
}
}