Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@lionralfs/discogs-client

lionralfs535MIT4.1.2TypeScript support: included

A full-featured Discogs API v2.0 client library

discogs, api, client, oauth

readme

npm npm type definitions node-current Libraries.io dependency status for latest release build status

discogs-client

About

discogs-client is a Node.js and browser client library that connects with the Discogs.com API v2.0.

This library is a fork of the original library which does the following:

  • uses ES Modules
  • uses esbuild to provide a bundle that is consumable by either:
    • node via ESM
    • node via CommonJS
    • browsers (where node-fetch is replaced with native window.fetch)
  • uses TypeScript (and generating type declarations) for typed parameters and API results
  • adds docs and type info via JSDoc (for non-TypeScript users)
  • removes callbacks in favor of Promises
  • adds support for all remaining Discogs endpoints
  • adds more tests

Features

  • Covers all API endpoints
  • Supports pagination, rate limiting and throttling
  • API calls return a native JS Promise
  • Easy access to protected endpoints with Discogs Auth
  • Includes OAuth 1.0a tools. Just plug in your consumer key and secret and do the OAuth dance
  • API functions grouped in their own namespace for easy access and isolation

Installation

npm install @lionralfs/discogs-client

Usage

Quick start

Here are some basic usage examples that connect with the public API. Error handling has been left out for demonstrational purposes.

Importing the library

// in modern JS/TS
import { DiscogsClient } from '@lionralfs/discogs-client';

// in commonjs environments
const { DiscogsClient } = require('@lionralfs/discogs-client/commonjs');

// in browser environments
import { DiscogsClient } from '@lionralfs/discogs-client/browser';

Go!

Get the release data for a release with the id 176126.

let db = new DiscogsClient().database();
db.getRelease(176126).then(function ({ rateLimit, data }) {
    console.log(data);
});

Set your own custom User-Agent. This is optional as when omitted it will set a default one with the value @lionralfs/discogs-client/x.x.x where x.x.x is the installed version of this library.

let client = new DiscogsClient({ userAgent: 'MyUserAgent/1.0' });

Get page 2 of USER_NAME's public collection showing 75 releases. The second param is the collection folder ID where 0 is always the "All" folder.

let col = new DiscogsClient().user().collection();
col.getReleases('USER_NAME', 0, { page: 2, per_page: 75 }).then(function ({ data }) {
    console.log(data);
});

Promises

The API functions return a native JS Promise for easy chaining.

let db = client.database();
db.search({ query: 'dark side of the moon', type: 'master' })
    .then(function ({ data }) {
        return db.getMaster(data.results[0].id);
    })
    .then(function ({ data }) {
        return db.getArtist(data.artists[0].id);
    })
    .then(function ({ data }) {
        console.log(data.name);
    });

Output format

User, artist and label profiles can be formatted in different ways: plaintext, html and discogs. The client defaults to discogs, but the output format can be set for each client instance.

// Set the output format to HTML
let client = new DiscogsClient().setConfig({ outputFormat: 'html' });

Discogs Auth

Just provide the client constructor with your preferred way of authentication.

// Authenticate by user token
let client = new DiscogsClient({ auth: { userToken: 'YOUR_USER_TOKEN' } });

// Authenticate by consumer key and secret
let client = new DiscogsClient({
    auth: {
        method: 'discogs',
        consumerKey: 'YOUR_CONSUMER_KEY',
        consumerSecret: 'YOUR_CONSUMER_SECRET',
    },
});

The User-Agent can still be passed for authenticated calls.

let client = new DiscogsClient({
    userAgent: 'MyUserAgent/1.0',
    auth: { userToken: 'YOUR_USER_TOKEN' },
});

OAuth

Below are the steps that involve getting a valid OAuth access token from Discogs.

1. Get a request token

let oAuth = new DiscogsOAuth('YOUR_CONSUMER_KEY', 'YOUR_CONSUMER_SECRET');
let { token, tokenSecret, authorizeUrl } = await oAuth.getRequestToken('https://your-domain.com/callback');

// store token and tokenSecret in a cookie for example
// redirect user to authorizeUrl

2. Authorize

After redirection to the Discogs authorize URL in step 1, authorize the application.

3. Get an access token

// in the callback endpoint, capture the oauth_verifier query parameter
// use the token and tokenSecret from step 1 to get an access token/secret
let { accessToken, accessTokenSecret } = await oAuth.getAccessToken(token, tokenSecret, oauth_verifier);

4. Make OAuth calls

Instantiate a new DiscogsClient class with the required auth arguments to make requests on behalf of the authenticated user.

let client = new DiscogsClient({
    auth: {
        method: 'oauth',
        consumerKey: consumerKey,
        consumerSecret: consumerSecret,
        accessToken: accessToken,
        accessTokenSecret: accessTokenSecret,
    },
});

let response = await client.getIdentity();
console.log(response.data.username);

Pagination

Discogs paginates certain collections, as they would otherwise be too much to return for a single API call. You may use the page and per_page options in each call to query certain pages. If you don't pass these options, they fall back to the Discogs defaults, which are 1 and 50 respectively (the first 50 results on the first page).

In the result.data object, you'll find a pagination key, which contains some info returned by the Discogs API such as the total number of items and pages.

Here's a short example of how to use pagination arguments:

// retrieves an artist's releases (25 per page, 2nd page)
let result = await client.database().getArtistReleases(108713, { per_page: 25, page: 2 });

console.log(result.data.pagination);
// {
//   page: 2,
//   pages: 54,
//   per_page: 25,
//   items: 1331,
//   urls: {
//     first: 'https://api.discogs.com/artists/108713/releases?per_page=25&page=1',
//     last: 'https://api.discogs.com/artists/108713/releases?per_page=25&page=54',
//     prev: 'https://api.discogs.com/artists/108713/releases?per_page=25&page=1',
//     next: 'https://api.discogs.com/artists/108713/releases?per_page=25&page=3'
//   }
// }

Rate Limiting

The Discogs API imposes certain rate limits on consumers, varying in allowed calls per minute depending on your authentication status. The API responds with your current quota in HTTP headers for each API call. These are passed to you as a rateLimit object on the response:

let response = await client.database().getArtistReleases(108713);
console.log(response.rateLimit); // → { limit: 25, used: 4, remaining: 21 }

Throttling

The client implements exponential backoff when encountering Discogs-API responses with status code 429 Too Many Requests. The exponential backoff can be configured via the following parameters:

client.setConfig({
    exponentialBackoffIntervalMs: 2000,
    exponentialBackoffMaxRetries: 5,
    exponentialBackoffRate: 2.7,
});

Note: By default, the exponentialBackoffMaxRetries is 0, essentially turning off throttling.

Structure

The global library structure looks as follows:

new DiscogsClient() -> database()
                        -> getArtist
                        -> getArtistReleases
                        -> getRelease
                        -> getReleaseRating
                        -> setReleaseRating
                        -> getReleaseCommunityRating
                        -> getReleaseStats
                        -> getMaster
                        -> getMasterVersions
                        -> getLabel
                        -> getLabelReleases
                        -> search
                    -> marketplace()
                        -> getInventory
                        -> getListing
                        -> addListing
                        -> editListing
                        -> deleteListing
                        -> getOrders
                        -> getOrder
                        -> editOrder
                        -> getOrderMessages
                        -> addOrderMessage
                        -> getFee
                        -> getPriceSuggestions
                        -> getReleaseStats
                    -> inventory()
                        -> exportInventory
                        -> getExports
                        -> getExport
                        -> downloadExport
                    -> user()
                        -> getProfile
                        -> editProfile
                        -> getInventory
                        -> getIdentity
                        -> getContributions
                        -> getSubmissions
                        -> getLists
                        -> collection()
                            -> getFolders
                            -> getFolder
                            -> addFolder
                            -> setFolderName
                            -> deleteFolder
                            -> getReleases
                            -> getReleaseInstances
                            -> addRelease
                            -> editRelease
                            -> removeRelease
                            -> getFields
                            -> editInstanceNote
                            -> getValue
                        -> wantlist()
                            -> getReleases
                            -> addRelease
                            -> editNotes
                            -> removeRelease
                        -> list()
                            -> getItems
new DiscogsOAuth()  -> getRequestToken
                    -> getAccessToken

Resources

License

MIT

changelog

4.1.1 / 2024-08-08

4.1.0 / 2024-05-19

4.0.0 / 2023-12-28

3.1.3 / 2023-10-30

3.1.2 / 2023-05-18

3.1.1 / 2023-04-30

3.1.0 / 2023-04-14

3.0.4 / 2023-04-02

3.0.3 / 2022-11-23

3.0.2 / 2022-11-16

3.0.1 / 2022-11-11

3.0.0 / 2022-10-30

  • Removed Node.js 12 support

2.0.2 / 2022-10-30

  • Updated dependencies

2.0.1 / 2022-09-18

  • Updated dependencies

2.0.0 / 2022-05-21

  • Initial fork release. Includes large refactoring:
    • uses ES Modules
    • uses esbuild to provide a bundle that is consumable by either:
      • node via ESM
      • node via CommonJS
      • browsers (where node-fetch is replaced with native window.fetch)
    • uses TypeScript (and generating type declarations) for typed parameters and API results
    • adds docs and type info via JSDoc (for non-TypeScript users)
    • removes callbacks in favor of Promises
    • adds support for all remaining Discogs endpoints
    • adds more tests
    • remove database().getImage

1.2.2 / 2021-02-04

  • Fixed accept headers for non-json data

1.2.1 / 2017-09-04

  • Fixed bug in image downloads (and any url different from api.discogs.com)

1.2.0 / 2017-06-07

  • Query parameter is now optional for database.search()
  • Implemented different request limits for authenticated and non-authenticated clients

1.1.0 / 2017-02-23

  • Implemented new Discogs rate limiting headers. The rate limit param in a callback now looks like: { limit: 240, used: 1, remaining: 239 }

1.0.2 / 2016-11-10

  • Added collection().getReleaseInstances()

1.0.1 / 2016-11-03

  • Fixed issue with database().search() when using a Promise

1.0.0 / 2016-10-27

  • When no callback is provided, all API functions now return a native JS Promise
  • Removed the non get/set method calls like database.release(...) deprecated in release 0.8.0

0.9.1 / 2016-10-24

  • Upgraded OAuth library to oauth-1.0a v2.0.0

0.9.0 / 2016-06-15

  • Added user().getLists()
  • Added the new user().list() namespace for other list functions. Currently only contains getItems().

0.8.0 / 2016-04-13

  • Added the new release rating endpoints
  • Changed a lot of function names to more consistent ones. Old function calls still work, but a deprecation notice is shown on the console and the old function names will be removed in the next major version.

0.7.2 / 2016-02-09

  • Fixed default maximum number of requests per minute

0.7.1 / 2016-01-26

  • Added database().labelReleases() function

0.7.0 / 2016-01-25

  • The util.queue object literal has been replaced by a minimal util.Queue class
  • DiscogsClient now has two new config params requestLimit and requestLimitInterval

0.6.8 / 2015-11-06

  • Dependency updates
  • Fixed a minor bug in DiscogsClient.authenticated()

0.6.7 / 2015-09-15

  • Fixed regression bug from version 0.6.6 involving double URL query string encoding in database().search()

0.6.6 / 2015-08-31

  • An empty search query in database().search() will no longer add the q= param to the search URL

0.6.5 / 2015-08-27

  • Fixed a bug in util.merge()

0.6.4 / 2015-07-09

  • Prevent JSON.parse() crash when the Discogs API returns HTML instead of json (maintainance mode)
  • Added Discogs API version to DiscogsClient config (only the default v2 is supported at the moment)

0.6.3 / 2015-05-28

  • Updated oauth-1.0a dependency

0.6.2 / 2015-02-25

  • database().image() now requires the full image url as the first parameter due to the new Discogs image cluster
  • Local request throttling by disconnect has been disabled for database().image()

0.6.1 / 2015-02-17

  • Added setting output format for user, artist and label profiles through DiscogsClient.setConfig({outputFormat: 'html'})

0.6.0 / 2015-01-19

  • OAuth authentication is no longer embedded in DiscogsClient
  • Added OAuth signature method configuration option
  • Added support for the new Discogs Auth authentication methods
  • Changed default OAuth signature method to PLAINTEXT due to problems with HMAC-SHA1 + database search

0.5.3 / 2014-12-02

  • Fixed incorrect assumption that a Discogs order ID is numeric in marketplace().orders()

0.5.2 / 2014-10-30

  • Fixed incorrect reference to this from within a callback function in DiscogsClient.about()
  • The internal oauth object of DiscogsClient now only gets 3 status values: null, request and access

0.5.1 / 2014-10-29

  • Fixed a test which was failing due to changes in 0.5.0 and npm test now runs the tests
  • Added the possibility to set a custom configuration object with DiscogsClient.setConfig() for Browserify + CORS or Proxy use cases
  • Updated README.md to explain the app variable

0.5.0 / 2014-10-22

  • Replaced some short circuit evaluations and improved the general readability of client.js
  • Implemented a more elegant way to require OAuth authentication for the get(), post(), put() and delete() functions of DiscogsClient
  • Breaking change: DiscogsClient.getAccessToken() now only acceps two parameters: verifier and callback. The former requestObject parameter is now taken from the oauth property of the DiscogsClient instance. For further info see the updated README.md

0.4.2 / 2014-10-20

  • Fixed this scoping in about()
  • Switched from http to the newly implemented https Discogs API connection for added security

0.4.1 / 2014-10-16

  • Fixed "Unexpected token u" error when trying to parse an undefined response value to JSON
  • marketplace().fee() now accepts the price argument as both a number (int/float) and a literal string

0.4.0 / 2014-10-15

  • Use strict
  • Added local authentication check for the database().search() function

0.3.4 / 2014-07-30

  • Added user().contributions() and user().submissions() for the newly implemented endpoints

0.3.3 / 2014-07-08

  • Discogs has fixed the /images/<filename> endpoint, so changed database().image() accordingly

0.3.2 / 2014-07-01

  • Added about() function to get general info about the Discogs API and the disconnect client

0.3.1 / 2014-06-26

  • Fixed a little bug in the calculation of free positions in the request queue
  • Started adding unit tests using wru

0.3.0 / 2014-06-24

  • Added automatic request throttle of 1 request per second queueing up to 10 requests
  • Exposed the request queueing functions in util.queue

0.2.1 / 2014-06-20

  • Fixed data encoding bug for gzipped response from 0.2.0
  • First implementation of generic error handling using custom Error objects containing the HTTP status code

0.2.0 / 2014-06-19

  • Implemented/fixed broken database().image() function from 0.1.1
  • Added rate limiting header info to the callback params

0.1.1 / 2014-06-18

  • Added HISTORY.md
  • Fixed some object reference bugs
  • Compacted the DiscogsClient constructor
  • Added the collection folder functions
  • Added the image function to the database namespace

0.1.0 / 2014-06-18

  • Initial public release