96 lines
2.3 KiB
Go
96 lines
2.3 KiB
Go
// Package client provides a client for interacting with the Pokémon TCG database.
|
|
package client
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"net/http"
|
|
|
|
"github.com/kratisto/tcgdex-golang/models"
|
|
)
|
|
|
|
const (
|
|
defaultURL = "https://api.tcgdex.net/v2/fr"
|
|
defaultLanguage = "en"
|
|
)
|
|
|
|
// TCGDexClient is the interface for interacting with the Pokémon TCG database.
|
|
type TCGDexClient interface {
|
|
CardsClient
|
|
SeriesClient
|
|
SetsClient
|
|
}
|
|
|
|
// CardsClient is the interface for card-related operations.
|
|
type CardsClient interface {
|
|
GetCard(ctx context.Context, id string) (*models.Card, error)
|
|
Cards(ctx context.Context) ([]*models.Card, error)
|
|
}
|
|
|
|
// SeriesClient is the interface for series-related operations.
|
|
type SeriesClient interface {
|
|
Series(ctx context.Context) ([]*models.Serie, error)
|
|
GetSerie(ctx context.Context, seriesID string) (*models.Serie, error)
|
|
}
|
|
|
|
// SetsClient is the interface for set-related operations.
|
|
type SetsClient interface {
|
|
Sets(ctx context.Context) ([]*models.Set, error)
|
|
GetSet(ctx context.Context, setID string) (*models.Set, error)
|
|
GetCardOfSet(ctx context.Context, setID string, cardID string) (*models.Card, error)
|
|
}
|
|
|
|
type tcgDexClient struct {
|
|
CardsClient
|
|
SeriesClient
|
|
SetsClient
|
|
|
|
baseURL string
|
|
language string
|
|
httpClient *http.Client
|
|
}
|
|
|
|
// NewClient creates a new TCGDexClient with the default http client.
|
|
func NewClient(baseURL string, language string) TCGDexClient {
|
|
return &tcgDexClient{
|
|
baseURL: baseURL,
|
|
language: language,
|
|
httpClient: http.DefaultClient,
|
|
}
|
|
}
|
|
|
|
// NewClientWithCustomHTTPClient creates a new TCGDexClient with a custom HTTP client.
|
|
// This allows for more control over the HTTP requests, such as setting timeouts or custom headers.
|
|
func NewClientWithCustomHTTPClient(url string, language string, client *http.Client) TCGDexClient {
|
|
return &tcgDexClient{
|
|
baseURL: url,
|
|
language: language,
|
|
httpClient: client,
|
|
}
|
|
}
|
|
|
|
func doRequest[T any](client *http.Client, request *http.Request) (T, error) {
|
|
var result T
|
|
|
|
resp, err := client.Do(request)
|
|
if err != nil {
|
|
return result, err
|
|
}
|
|
|
|
defer func() {
|
|
err := resp.Body.Close()
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
}()
|
|
|
|
jsonDecoder := json.NewDecoder(resp.Body)
|
|
|
|
err = jsonDecoder.Decode(&result)
|
|
if err != nil {
|
|
return result, err
|
|
}
|
|
|
|
return result, nil
|
|
}
|