discogs

package module
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 6, 2024 License: MIT Imports: 13 Imported by: 0

README

discogs

A Go SDK for interacting with the Discogs API.

This project is in its beginning state. More API endpoints will be added in the future. There is currently only support for consumer key/secret authentication.

Features

  • Handle rate limiting automatically

Installation

To install the SDK, use go get:

go get github.com/couwuch/discogs

Documentation

Overview

Package discogs provides a client library for interacting with the Discogs API.

The Discogs API allows developers to access and manage data related to music releases, artists, labels, and more. This package simplifies the process of making HTTP requests to the Discogs API by providing a structured client that handles authentication, parameterized routes, and response parsing. More information can be found at the Discogs developers page.

Index

Constants

View Source
const (
	TypeRelease = "release"
	TypeMaster  = "master"
	TypeArtist  = "artist"
	TypeLabel   = "label"
)

Type constants representing various entity types.

View Source
const (
	BaseURL         = "https://api.discogs.com"
	DefaultAppName  = "DiscogsGo/0.1"
	AuthHeader      = "Authorization"
	UserAgentHeader = "User-Agent"
	RateLimitHeader = "X-Discogs-Ratelimit"
	RateLimitUnauth = 25
	RateLimitAuth   = 60
)

Variables

View Source
var EndpointAuthMap = map[string]AuthType{
	"/test":                  AuthTypeNone,
	"/releases/{release_id}": AuthTypeNone,
	"/database/search":       AuthTypeKeySecret,
}

endpointAuthMap maps API endpoints to their required authentication types.

Functions

This section is empty.

Types

type AuthType

type AuthType string

AuthType represents the type of authentication required for an endpoint.

const (
	AuthTypeUnknown   AuthType = "unknown"
	AuthTypeNone      AuthType = "none"
	AuthTypeKeySecret AuthType = "key-secret"
	AuthTypeOAuth     AuthType = "oauth"
	AuthTypePAT       AuthType = "personal-access-token"
)

type Currency

type Currency string

Currency represents a currency code used in the Discogs API.

const (
	CurrencyUSD Currency = "USD"
	CurrencyGBP Currency = "GBP"
	CurrencyEUR Currency = "EUR"
	CurrencyCAD Currency = "CAD"
	CurrencyAUD Currency = "AUD"
	CurrencyJPY Currency = "JPY"
	CurrencyCHF Currency = "CHF"
	CurrencyMXN Currency = "MXN"
	CurrencyBRL Currency = "BRL"
	CurrencyNZD Currency = "NZD"
	CurrencySEK Currency = "SEK"
	CurrencyZAR Currency = "ZAR"
)

Currency constants representing various supported currencies.

type DiscogsClient

type DiscogsClient struct {
	*http.Client
	Host   string
	Config DiscogsConfig
	// contains filtered or unexported fields
}

DiscogsClient is a wrapper for http.Client that includes the Host of the API and a Config for the client. It also includes a rateLimiter to rate limit requests.

func NewDiscogsClient

func NewDiscogsClient(config *DiscogsConfig) *DiscogsClient

NewDiscogsClient creates a new DiscogsClient with the provided configuration. If AppName is not provided in the config, it defaults to DefaultAppName. TODO: handle AccessToken

func (*DiscogsClient) Delete

func (dc *DiscogsClient) Delete(ctx context.Context, endpoint string, params url.Values, headers map[string]string, res interface{}) error

Delete sends an HTTP DELETE request to the specified endpoint with the given parameters and headers, and unmarshals the response into the provided res interface.

func (*DiscogsClient) Do

func (dc *DiscogsClient) Do(ctx context.Context, req *http.Request, res interface{}) error

Do sends an HTTP request and unmarshals the response into the provided res interface. It respects the rate limits by waiting until the rate limiter allows the request. It also updates the rate limiter based on the X-Discogs-Ratelimit header from the API response. It returns an HTTPError if the response status code is not 2xx.

func (*DiscogsClient) Get

func (dc *DiscogsClient) Get(ctx context.Context, endpoint string, params url.Values, headers map[string]string, res interface{}) error

Get sends an HTTP GET request to the specified endpoint with the given parameters and headers, and unmarshals the response into the provided res interface.

func (*DiscogsClient) Limit

func (dc *DiscogsClient) Limit() rate.Limit

Limit returns the current rate limit of the DiscogsClient.

func (*DiscogsClient) Post

func (dc *DiscogsClient) Post(ctx context.Context, endpoint string, params url.Values, headers map[string]string, body, res interface{}) error

Post sends an HTTP POST request to the specified endpoint with the given parameters, headers, and body, and unmarshals the response into the provided res interface.

func (*DiscogsClient) Put

func (dc *DiscogsClient) Put(ctx context.Context, endpoint string, params url.Values, headers map[string]string, body, res interface{}) error

Put sends an HTTP PUT request to the specified endpoint with the given parameters, headers, and body, and unmarshals the response into the provided res interface.

func (*DiscogsClient) Release

func (dc *DiscogsClient) Release(ctx context.Context, releaseID int64, options *ReleaseOptions) (*ReleaseResponse, error)

Release fetches detailed information about a release from the Discogs database by sending a GET request to the /releases/{release_id} endpoint. The releaseID specifies the ID of the release to fetch, and options allows for additional query parameters. The context.Context provides control over the request's lifecycle. It returns a pointer to a ReleaseResponse struct containing the release details, or an error if the request fails or the release is not found.

Documentation: https://www.discogs.com/developers#page:database,header:database-release

func (*DiscogsClient) Search

func (dc *DiscogsClient) Search(ctx context.Context, options *SearchOptions) (*SearchResponse, error)

Search performs a search query against the Discogs database by sending a GET request to the /database/search endpoint. The options parameter specifies the search options, such as query and type. The context.Context provides control over the request's lifecycle. It returns a pointer to a SearchResponse struct containing the search results, or an error if the request fails.

func (*DiscogsClient) SetMaxRequests

func (dc *DiscogsClient) SetMaxRequests(requestsPerMinute int)

SetMaxRequests allows the user to set a custom rate limit for the DiscogsClient. It adjusts the rate limiter to the specified number of requests per minute.

func (*DiscogsClient) Tokens

func (dc *DiscogsClient) Tokens() float64

Tokens returns the number of tokens (available requests) currently in the rate limiter's bucket.

type DiscogsConfig

type DiscogsConfig struct {
	// Provided as User-Agent string to identify the application to Discogs.
	// Preferably follows [RFC 1945].
	//
	// Example: MyDiscogsClient/1.0 +http://mydiscogsclient.org
	//
	// [RFC 1945]: http://tools.ietf.org/html/rfc1945#section-3.7
	AppName        string
	ConsumerKey    *string
	ConsumerSecret *string
	AccessToken    *string
	MaxRequests    int
}

DiscogsConfig contains configuration options for the Discogs client.

TODO: add support for AccessToken and OAuth tokens.

type ErrMatchNotFound

type ErrMatchNotFound struct {
	Endpoint string
}

ErrMatchNotFound represents an error when no matching route is found for authentication.

func (*ErrMatchNotFound) Error

func (e *ErrMatchNotFound) Error() string

type ErrMissingCredentials

type ErrMissingCredentials struct {
	RequiredAuthType AuthType
	Endpoint         string
}

ErrMissingCredentials represents an error when credentials required for an endpoint are missing from the DiscogsConfig.

func (*ErrMissingCredentials) Error

func (e *ErrMissingCredentials) Error() string

type ErrReleaseNotFound

type ErrReleaseNotFound struct {
	ReleaseID int
	*HTTPError
}

ErrReleaseNotFound indicates that a release with the specified ID was not found.

func (*ErrReleaseNotFound) Error

func (e *ErrReleaseNotFound) Error() string

Error returns a formatted error message indicating that the release was not found.

type HTTPError

type HTTPError struct {
	StatusCode int
	Message    string
}

An HTTPError provides information on an error resulting from an HTTP request, including the StatusCode and Message.

func (*HTTPError) Error

func (e *HTTPError) Error() string

Error provides a human digestible string of an HTTPError.

Example: "HTTP 404: Item not found".

type Pagination

type Pagination struct {
	Page    int64 `json:"page"`
	Pages   int64 `json:"pages"`
	Items   int64 `json:"items"`
	PerPage int64 `json:"per_page"`
	Urls    *struct {
		First string `json:"first"`
		Prev  string `json:"prev"`
		Next  string `json:"next"`
		Last  string `json:"last"`
	} `json:"urls"`
}

Pagination represents the pagination information returned by the Discogs API.

See https://www.discogs.com/developers#page:home,header:home-pagination

type PaginationParams

type PaginationParams struct {
	Page    *int `url:"page,omitempty"`
	PerPage *int `url:"per_page,omitempty"` // The number of items per page. Default is 50. Maximum is 100.
}

PaginationParams represents the pagination parameters for API requests.

type ReleaseOptions

type ReleaseOptions struct {
	CurrAbr Currency `url:"curr_abbr,omitempty"`
}

ReleaseOptions represents the options for retrieving a release.

type ReleaseResponse

type ReleaseResponse struct {
	Title   string `json:"title"`
	ID      int64  `json:"id"`
	Artists []struct {
		ANV         string `json:"anv"`
		ID          *int64 `json:"id"`
		Join        string `json:"join"`
		Name        string `json:"name"`
		ResourceURL string `json:"resource_url"`
		Role        string `json:"role"`
		Tracks      string `json:"tracks"`
	} `json:"artists"`
	DataQuality string `json:"data_quality"`
	Thumb       string `json:"thumb"`
	Community   *struct {
		Contributors []struct {
			ResourceURL string `json:"resource_url"`
			Username    string `json:"username"`
		} `json:"contributors"`
		DataQuality string `json:"data_quality"`
		Have        *int64 `json:"have"`
		Rating      *struct {
			Average *float64 `json:"average"`
			Count   *int64   `json:"count"`
		} `json:"rating"`
		Status    *string `json:"status"`
		Submitter *struct {
			ResourceURL string `json:"resource_url"`
			Username    string `json:"username"`
		} `json:"submitter"`
		Want *int64 `json:"want"`
	} `json:"community"`
	Companies []struct {
		CatNo          string `json:"catno"`
		EntityType     string `json:"entity_type"`
		EntityTypeName string `json:"entity_type_name"`
		ID             *int64 `json:"id"`
		Name           string `json:"name"`
		ResourceURL    string `json:"resource_url"`
	} `json:"companies"`
	Country         string     `json:"country"`
	DateAdded       *time.Time `json:"date_added"`
	DateChanged     *time.Time `json:"date_changed"`
	EstimatedWeight *int64     `json:"estimated_weight"`
	ExtraArtists    []struct {
		ANV         string `json:"anv"`
		ID          *int64 `json:"id"`
		Join        string `json:"join"`
		Name        string `json:"name"`
		ResourceURL string `json:"resource_url"`
		Role        string `json:"role"`
		Tracks      string `json:"tracks"`
	} `json:"extraartists"`
	FormatQuantity *int64 `json:"format_quantity"`
	Formats        []struct {
		Descriptions []string `json:"descriptions"`
		Name         string   `json:"name"`
		Qty          string   `json:"qty"`
	} `json:"formats"`
	Genres      []string `json:"genres"`
	Identifiers []struct {
		Type  string `json:"type"`
		Value string `json:"value"`
	} `json:"identifiers"`
	Images []struct {
		Height      *int64 `json:"height"`
		ResourceURL string `json:"resource_url"`
		Type        string `json:"type"`
		URI         string `json:"uri"`
		URI150      string `json:"uri150"`
		Width       *int64 `json:"width"`
	} `json:"images"`
	Labels []struct {
		CatNo       string `json:"catno"`
		EntityType  string `json:"entity_type"`
		ID          *int64 `json:"id"`
		Name        string `json:"name"`
		ResourceURL string `json:"resource_url"`
	} `json:"labels"`
	LowestPrice       *float64      `json:"lowest_price"`
	MasterID          *int64        `json:"master_id"`
	MasterURL         string        `json:"master_url"`
	Notes             string        `json:"notes"`
	NumForSale        *int64        `json:"num_for_sale"`
	Released          string        `json:"released"`
	ReleasedFormatted string        `json:"released_formatted"`
	ResourceURL       string        `json:"resource_url"`
	Series            []interface{} `json:"series"`
	Status            string        `json:"status"`
	Styles            []string      `json:"styles"`
	Tracklist         []struct {
		Duration string `json:"duration"`
		Position string `json:"position"`
		Title    string `json:"title"`
		Type_    string `json:"type_"`
	} `json:"tracklist"`
	URI    string `json:"uri"`
	Videos []struct {
		Description string `json:"description"`
		Duration    *int64 `json:"duration"`
		Embed       *bool  `json:"embed"`
		Title       string `json:"title"`
		URI         string `json:"uri"`
	} `json:"videos"`
	Year *int64 `json:"year"`
}

ReleaseResponse represents the response from the Discogs API for a release.

type SearchOptions

type SearchOptions struct {
	Pagination   PaginationParams
	Query        string `url:"q,omitempty"`
	Type         Type   `url:"type,omitempty"`
	Title        string `url:"title,omitempty"`
	ReleaseTitle string `url:"release_title,omitempty"`
	Credit       string `url:"credit,omitempty"`
	Artist       string `url:"artist,omitempty"`
	ANV          string `url:"anv,omitempty"`
	Label        string `url:"label,omitempty"`
	Genre        string `url:"genre,omitempty"`
	Style        string `url:"style,omitempty"`
	Country      string `url:"country,omitempty"`
	Year         string `url:"year,omitempty"`
	Format       string `url:"format,omitempty"`
	CatNo        string `url:"catno,omitempty"`
	Barcode      string `url:"barcode,omitempty"`
	Track        string `url:"track,omitempty"`
	Submitter    string `url:"submitter,omitempty"`
	Contributor  string `url:"contributor,omitempty"`
}

SearchOptions represents the options for performing a search query in the Discogs database.

type SearchResponse

type SearchResponse struct {
	Pagination *Pagination    `json:"pagination"`
	Results    []SearchResult `json:"results"`
}

SearchResponse represents the response from the Discogs API for a search query.

type SearchResult

type SearchResult struct {
	Style     []string `json:"style"`
	Thumb     string   `json:"thumb"`
	Title     string   `json:"title"`
	Country   string   `json:"country"`
	Format    []string `json:"format"`
	URI       string   `json:"uri"`
	Community struct {
		Want *int64 `json:"want"`
		Have *int64 `json:"have"`
	} `json:"community"`
	Label       []string `json:"label"`
	CatNo       string   `json:"catno"`
	Year        string   `json:"year"`
	Genre       []string `json:"genre"`
	ResourceURL string   `json:"resource_url"`
	Type        Type     `json:"type"`
	ID          *int64   `json:"id"`
}

SearchResult represents a single result from a search query.

type Type

type Type string

Type represents a type of entity in the Discogs database.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL