Skip to content

Commit

Permalink
Merge pull request #166 from twitchdev/bugfix/157-extension-cursor
Browse files Browse the repository at this point in the history
Fixing #157 and various test improvements
  • Loading branch information
Xemdo authored Aug 26, 2022
2 parents ba27ba9 + 6c03e9b commit d8e422a
Show file tree
Hide file tree
Showing 12 changed files with 72 additions and 25 deletions.
55 changes: 46 additions & 9 deletions internal/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ func NewRequest(method string, path string, queryParameters []string, body []byt
var err error
var cursor string

isExtensionsEndpoint := false // https://github.com/twitchdev/twitch-cli/issues/157

data.Data = make([]interface{}, 0)
client, err := GetClientInformation()
if err != nil {
Expand Down Expand Up @@ -100,11 +102,30 @@ func NewRequest(method string, path string, queryParameters []string, body []byt
fmt.Println("Endpoint responded with status 204")
return
}

err = json.Unmarshal(resp.Body, &apiResponse)
if err != nil {
fmt.Printf("Error unmarshalling body: %v", err)
return
if strings.Contains(u.String(), "extensions/live") {
// https://github.com/twitchdev/twitch-cli/issues/157
isExtensionsEndpoint = true
var extensionsBody models.ExtensionAPIResponse
err = json.Unmarshal(resp.Body, &extensionsBody)
if err != nil {
fmt.Printf("Error unmarshalling body: %v", err)
return
}
apiResponse = models.APIResponse{
Data: extensionsBody.Data,
Status: extensionsBody.Status,
Error: extensionsBody.Error,
Message: extensionsBody.Message,
Pagination: &models.APIPagination{
Cursor: *extensionsBody.Pagination,
},
}
} else {
err = json.Unmarshal(resp.Body, &apiResponse)
if err != nil {
fmt.Printf("Error unmarshalling body: %v", err)
return
}
}

if runCounter == 1 {
Expand Down Expand Up @@ -158,10 +179,26 @@ func NewRequest(method string, path string, queryParameters []string, body []byt
data.Data = make([]interface{}, 0)
}

d, err := json.Marshal(data)
if err != nil {
log.Printf("Error marshalling json: %v", err)
return
var d []byte
if isExtensionsEndpoint {
extensionBody := models.ExtensionAPIResponse{
Data: data.Data,
Pagination: &data.Pagination.Cursor,
Error: data.Error,
Status: data.Status,
Message: data.Message,
}
d, err = json.Marshal(extensionBody)
if err != nil {
log.Printf("Error marshalling json: %v", err)
return
}
} else {
d, err = json.Marshal(data)
if err != nil {
log.Printf("Error marshalling json: %v", err)
return
}
}

if prettyPrint {
Expand Down
4 changes: 3 additions & 1 deletion internal/api/api_request.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ type apiRequestResponse struct {

func apiRequest(method string, url string, payload []byte, p apiRequestParameters) (apiRequestResponse, error) {
req, err := request.NewRequest(method, url, bytes.NewBuffer(payload))

if err != nil {
return apiRequestResponse{}, err
}
req.Header.Set("Client-ID", p.ClientID)
req.Header.Set("Content-Type", "application/json")
rl := rate.NewLimiter(rate.Every(time.Minute), 800)
Expand Down
2 changes: 1 addition & 1 deletion internal/api/api_request_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func TestApiRequest(t *testing.T) {

defer ts.Close()

params := *&apiRequestParameters{
params := apiRequestParameters{
ClientID: "1234",
Token: "4567",
}
Expand Down
3 changes: 2 additions & 1 deletion internal/api/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,10 @@ func TestNewClient(t *testing.T) {

body, err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
a.NoError(err)
a.Equal(ok, string(body), "Body mismatch")

req, _ = http.NewRequest(http.MethodGet, "potato", nil)
resp, err = c.Do(req)
_, err = c.Do(req)
a.NotNil(err)
}
2 changes: 1 addition & 1 deletion internal/database/authentication.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ func (q *Query) InsertOrUpdateAuthenticationClient(client AuthenticationClient,
db := q.DB

stmt := `insert into clients values(:id, :secret, :is_extension, :name)`
if upsert == true {
if upsert {
stmt += ` on conflict(id) do update set secret=:secret, is_extension:is_extension, name=:name`
}

Expand Down
2 changes: 1 addition & 1 deletion internal/database/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ func getDatabase() (sqlx.DB, error) {
continue
}

if needToInit == true {
if needToInit {
err = initDatabase(*db)
if err != nil {
log.Printf("%#v", err)
Expand Down
8 changes: 3 additions & 5 deletions internal/database/database_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,6 @@ func TestMain(m *testing.M) {
log.Fatal(err)
}

time.Sleep(10)

db, err = NewConnection()
if err != nil {
log.Print(err)
Expand Down Expand Up @@ -95,7 +93,7 @@ func TestMain(m *testing.M) {
func TestRetriveFromDB(t *testing.T) {
a := test_setup.SetupTestEnv(t)

ecParams := *&EventCacheParameters{
ecParams := EventCacheParameters{
ID: util.RandomGUID(),
Event: "foo",
JSON: "bar",
Expand Down Expand Up @@ -565,11 +563,11 @@ func TestQuery(t *testing.T) {

q.Set("before", query.PaginationCursor)
request.URL.RawQuery = q.Encode()
query = db.NewQuery(request, 100)
db.NewQuery(request, 100)

q.Set("after", "notbase64")
request.URL.RawQuery = q.Encode()
query = db.NewQuery(request, 100)
db.NewQuery(request, 100)
}

func TestStreams(t *testing.T) {
Expand Down
3 changes: 1 addition & 2 deletions internal/database/schedule.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ package database

import (
"database/sql"
"errors"
"time"
)

Expand Down Expand Up @@ -124,7 +123,7 @@ func (q *Query) UpdateSegment(p ScheduleSegment) error {
func (q *Query) GetVacations(p ScheduleSegment) (ScheduleVacation, error) {
v := ScheduleVacation{}
err := q.DB.Get(&v, "select id,starttime,endtime from stream_schedule where is_vacation=true and datetime(endtime) > datetime('now') and broadcaster_id= $1 limit 1", p.UserID)
if errors.As(err, &sql.ErrNoRows) {
if err == sql.ErrNoRows {
return v, nil
}
return v, err
Expand Down
2 changes: 1 addition & 1 deletion internal/database/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,7 @@ func (q *Query) SearchChannels(query string, live_only bool) (*DBResponse, error
r := []SearchChannel{}
stmt := `select u1.id, u1.user_login, u1.display_name, u1.category_id, u1.title, u1.stream_language, c.category_name, case when s.id is null then 'false' else 'true' end is_live, s.started_at from users u1 left join streams s on u1.id = s.broadcaster_id left join categories c on u1.category_id = c.id where lower(u1.user_login) like lower($1)`

if live_only == true {
if live_only {
stmt = `select u1.id, u1.user_login, u1.display_name, u1.category_id, u1.title, u1.stream_language, c.category_name, case when s.id is null then 'false' else 'true' end is_live, s.started_at from users u1 left join streams s on u1.id = s.broadcaster_id left join categories c on u1.category_id = c.id where lower(u1.user_login) like lower($1) and is_live='true'`
}

Expand Down
2 changes: 1 addition & 1 deletion internal/database/videos.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ func (q *Query) GetClips(c Clip, startDate string, endDate string) (*DBResponse,
if startDate != "" {
c.StartedAt = startDate
c.EndedAt = endDate
sql += fmt.Sprintf(" and datetime(c.created_at) > datetime(:started_at) and datetime(c.created_at) < datetime(:ended_at) ")
sql += " and datetime(c.created_at) > datetime(:started_at) and datetime(c.created_at) < datetime(:ended_at) "
}
sql += q.SQL
rows, err := q.DB.NamedQuery(sql, c)
Expand Down
6 changes: 4 additions & 2 deletions internal/mock_api/endpoints/channels/information.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ package channels
import (
"database/sql"
"encoding/json"
"log"
"net/http"

"github.com/mattn/go-sqlite3"
Expand Down Expand Up @@ -115,7 +114,6 @@ func patchInformation(w http.ResponseWriter, r *http.Request) {
return
}

log.Print("here")
var params PatchInformationEndpointRequest
err := json.NewDecoder(r.Body).Decode(&params)
if err != nil {
Expand All @@ -124,6 +122,10 @@ func patchInformation(w http.ResponseWriter, r *http.Request) {
}

u, err := db.NewQuery(r, 100).GetUser(database.User{ID: broadcasterID})
if err != nil {
mock_errors.WriteBadRequest(w, "Error writing request")
return
}

var gameID = u.CategoryID
if params.GameID == "" || params.GameID == "0" {
Expand Down
8 changes: 8 additions & 0 deletions internal/models/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,11 @@ type BitsLeaderboardDateRange struct {
StartedAt string `json:"started_at"`
EndedAt string `json:"ended_at"`
}

type ExtensionAPIResponse struct {
Data interface{} `json:"data,omitempty"`
Pagination *string `json:"pagination,omitempty"`
Error string `json:"error,omitempty"`
Status int `json:"status,omitempty"`
Message string `json:"message,omitempty"`
}

0 comments on commit d8e422a

Please sign in to comment.