go-twitch/api/predictions/get_predictions.go

76 lines
2.6 KiB
Go
Raw Normal View History

2024-03-03 15:50:12 -05:00
package predictions
import (
"context"
"encoding/json"
"fmt"
2024-03-03 15:50:12 -05:00
"net/http"
"net/url"
"github.com/google/go-querystring/query"
"go.fifitido.net/twitch/api/types"
)
type GetPredictionsParams struct {
// The ID of the broadcaster whose predictions you want to get. This ID must match the user ID in the user access token.
BroadcasterID string `url:"broadcaster_id"`
// The ID of the prediction to get.
// To specify more than one ID, include this parameter for each prediction you want to get. For example, id=1234&id=5678.
// You may specify a maximum of 25 IDs. The endpoint ignores duplicate IDs and those not owned by the broadcaster.
IDs []string `url:"id,omitempty"`
// The maximum number of items to return per page in the response.
// The minimum page size is 1 item per page and the maximum is 25 items per page.
// The default is 20.
First *int `url:"first,omitempty"`
// The cursor used to get the next page of results.
// The Pagination object in the response contains the cursors value.
// Read More: https://dev.twitch.tv/docs/api/guide#pagination
After *types.Cursor `url:"after,omitempty"`
}
type GetPredictionsResponse struct {
// The broadcasters list of Channel Points Predictions.
// The list is sorted in descending ordered by when the prediction began (the most recent prediction is first).
// The list is empty if the broadcaster hasnt created predictions.
Data []Prediction `json:"data"`
// A pagination object that contains the cursor to use to get the next page of results.
// The object is empty if there are no more pages left to page through.
// Read More: https://dev.twitch.tv/docs/api/guide#pagination
Pagination types.Pagination `json:"pagination"`
}
// Gets a list of Channel Points Predictions that the broadcaster created.
//
// Requires a user access token that includes the channel:read:predictions or channel:manage:predictions scope.
func (c *Predictions) GetPredictions(ctx context.Context, params *GetPredictionsParams) (*GetPredictionsResponse, error) {
v, _ := query.Values(params)
endpoint := c.baseUrl.ResolveReference(&url.URL{Path: "predictions", RawQuery: v.Encode()})
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint.String(), nil)
if err != nil {
return nil, err
}
res, err := c.client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
statusOK := res.StatusCode >= 200 && res.StatusCode < 300
if !statusOK {
return nil, fmt.Errorf("failed to get predictions (%d)", res.StatusCode)
}
2024-03-03 15:50:12 -05:00
var data GetPredictionsResponse
if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
return nil, err
}
return &data, nil
}