disconnect

repository·master·Indexed 19 days ago

https://github.com/bartve/disconnect

A full-featured Node.js client library for the Discogs API v2.0. It provides a structured, namespaced interface for interacting with Discogs databases, marketplaces, and user data, supporting both callbacks and Promises. The library includes modules for managing collection folders, querying artist and release data, handling marketplace listings and orders, and implementing OAuth 1.0a authentication.

Tokens
9.5K
Snippets
41
Records
43
Agent score
65%

What's inside disconnect

  1. How the disconnect library is structured

    master

    The library organizes API functions into namespaces for better isolation and access. The hierarchy is as follows:

    • Client
      • oauth()
      • database()
      • marketplace()
      • user()
        • collection()
          • wantlist()
          • list()
      • util
    require('disconnect') -> new Client() -> oauth()
                                          -> database()
                                          -> marketplace()
                                          -> user() -> collection()
                                                    -> wantlist()
                                                    -> list()
                          -> util
  2. Implement OAuth 1.0a flow

    master

    To use OAuth, follow these four steps:

    1. Get a request token: Use oauth.getRequestToken() with your consumer credentials and a callback URL. Redirect the user to the returned authorizeUrl.
    2. Authorize: The user authorizes your app on Discogs.
    3. Get an access token: In your callback route, use oauth.getAccessToken() with the oauth_verifier from the query string. Persist the resulting accessData.
    4. Make OAuth calls: Initialize a new Discogs client by passing the persisted accessData object to the constructor.
    // 1. Get a request token
    app.get('/authorize', function(req, res){
    	var oAuth = new Discogs().oauth();
    	oAuth.getRequestToken(
    		'YOUR_CONSUMER_KEY', 
    		'YOUR_CONSUMER_SECRET', 
    		'http://your-script-url/callback', 
    		function(err, requestData){
    			res.redirect(requestData.authorizeUrl);
    		}
    	);
    });
    
    // 3. Get an access token
    app.get('/callback', function(req, res){
    	var oAuth = new Discogs(requestData).oauth();
    	oAuth.getAccessToken(
    		req.query.oauth_verifier, 
    		function(err, accessData){
    			res.send('Received access token!');
    		}
    	);
    });
    
    // 4. Make OAuth calls
    app.get('/identity', function(req, res){
    	var dis = new Discogs(accessData);
    	dis.getIdentity(function(err, data){
    		res.send(data);
    	});
    });
  3. Authenticate with Discogs Auth

    master

    You can authenticate your client by providing credentials in the constructor. Supported methods include using a userToken or using a consumerKey and consumerSecret.

    Note: You can still pass a custom User-Agent as the first argument when providing an options object.

    var Discogs = require('disconnect').Client;
    
    // Authenticate by user token
    var dis = new Discogs({userToken: 'YOUR_USER_TOKEN'});
    
    // Authenticate by consumer key and secret
    var dis = new Discogs({
    	consumerKey: 'YOUR_CONSUMER_KEY', 
    	consumerSecret: 'YOUR_CONSUMER_SECRET'
    });
    
    // Authenticate with User-Agent and user token
    var dis = new Discogs('MyUserAgent/1.0', {userToken: 'YOUR_USER_TOKEN'});
  4. Initialize the Discogs Client

    master

    To use the library, require the Client class from disconnect. You can optionally provide a custom User-Agent string as the first argument to the constructor. If omitted, it defaults to DisConnectClient/x.x.x.

    var Discogs = require('disconnect').Client;
    
    // Basic initialization
    var dis = new Discogs();
    
    // Initialization with a custom User-Agent
    var disWithUA = new Discogs('MyUserAgent/1.0');
  5. Configure the output format

    master

    User, artist, and label profiles can be returned in plaintext, html, or discogs formats. The library defaults to discogs. You can set the format for a specific client instance using .setConfig({outputFormat: '...' }).

    var Discogs = require('disconnect').Client;
    // Set the output format to HTML
    var dis = new Discogs().setConfig({outputFormat: 'html'});
  6. Download images from Discogs

    master

    While image requests do not require authentication, you often need to authenticate to retrieve the image URLs (e.g., from release data). The db.getImage(url, callback) method returns the raw binary image data.

    var Discogs = require('disconnect').Client;
    var db = new Discogs(accessData).database();
    
    db.getRelease(176126, function(err, data){ 
    	var url = data.images[0].resource_url;
    	db.getImage(url, function(err, data, rateLimit){ 
    		// data contains the raw binary image data
    		require('fs').writeFile('/tmp/image.jpg', data, 'binary', function(err){ 
    			console.log('Image saved!');
    		});
    	});
    });
  7. Use Discogs API functions with callbacks

    master

    Most API functions follow the standard Node.js callback pattern: function(err, data, rateLimit).

    Example: Fetching release data from the database namespace:

    var Discogs = require('disconnect').Client;
    var db = new Discogs().database();
    
    db.getRelease(176126, function(err, data){ 
      // err: error object
      // data: release data
      console.log(data);
    });

    Example: Fetching a user's collection from the user().collection() namespace:

    var Discogs = require('disconnect').Client;
    var col = new Discogs().user().collection();
    
    // Params: username, folderId (0 for 'All'), options object
    col.getReleases('USER_NAME', 0, {page: 2, per_page: 75}, function(err, data){ 
      console.log(data);
    });
    var db = new Discogs().database();
    db.getRelease(176126, function(err, data){
    	console.log(data);
    });
  8. Use Promises for API calls

    master

    If you do not provide a callback function, disconnect returns a native JavaScript Promise. This allows for easy method chaining and cleaner asynchronous code.

    var Discogs = require('disconnect').Client;
    var db = new Discogs().database();
    
    db.getRelease(1)
    	.then(function(release){ 
    		return db.getArtist(release.artists[0].id);
    	})
    	.then(function(artist){
    		console.log(artist.name);
    	});
  9. Obtain an OAuth access token

    master

    After the user has authorized your application, they will be redirected back to you with a verifier code. Use getAccessToken to exchange this verifier for a permanent access token.

    Parameters:

    • verifier (string): The OAuth 1.0a verification code returned by Discogs.
    • callback (function, optional): A callback function receiving (err, auth).

    Behavior: Upon success, the internal auth object is updated with token, tokenSecret, and the level is set to 2.

    // 'verifier' is obtained from the callback URL after user authorization
    oauth.getAccessToken('VERIFIER_CODE', (err, auth) => {
      if (err) return console.error(err);
      console.log('Access Token:', auth.token);
      console.log('Token Secret:', auth.tokenSecret);
    });
  10. Manage marketplace orders and messages

    master

    Use these methods to handle transactions and communication within the marketplace.

    • getOrders([params], [callback]): Retrieve a list of the authenticated user's orders. params can be an object for sorting and pagination.
    • getOrder(order, [callback]): Get details for a specific order using the order ID (string).
    • editOrder(order, data, [callback]): Update an existing order using the order ID (string) and data object.
    • getOrderMessages(order, [params], [callback]): List messages associated with a specific order ID. params can be an object for pagination.
    • addOrderMessage(order, data, [callback]): Send a new message to a specific order ID using the data object.
    // Example: Getting orders and sending a message
    marketplace.getOrders({ limit: 10 }, (err, orders) => {
      const orderId = orders[0].id;
      
      marketplace.addOrderMessage(orderId, { message: 'Hello, I am shipping this today!' }, (err, msg) => {
        console.log('Message sent');
      });
    });
  11. Obtain an OAuth request token

    master

    The getRequestToken method initiates the OAuth flow by requesting a temporary token from Discogs.

    Parameters:

    • consumerKey (string): Your Discogs consumer key.
    • consumerSecret (string): Your Discogs consumer secret.
    • callbackUrl (string): The URL to redirect to after obtaining the token.
    • callback (function, optional): A callback function receiving (err, auth).

    Behavior: Upon success, the internal auth object is updated with token, tokenSecret, and an authorizeUrl which you should direct the user to visit to complete the authorization.

    oauth.getRequestToken(
      'YOUR_CONSUMER_KEY',
      'YOUR_CONSUMER_SECRET',
      'https://your-app.com/callback',
      (err, auth) => {
        if (err) return console.error(err);
        // Redirect user to auth.authorizeUrl
        console.log('Authorize here:', auth.authorizeUrl);
      }
    );