From ce110091812a91794338b9ff0b7a21477b0c4840 Mon Sep 17 00:00:00 2001 From: Bart van Eijck Date: Wed, 7 Jun 2017 13:50:55 +0200 Subject: [PATCH] 1.2.0 --- HISTORY.md | 4 + README.md | 2 +- lib/client.js | 497 ++++++++++++++++++++++++----------------------- lib/database.js | 345 ++++++++++++++++---------------- test/all.js | 2 +- test/client.js | 145 +++++--------- test/database.js | 56 ++++++ 7 files changed, 546 insertions(+), 505 deletions(-) create mode 100644 test/database.js diff --git a/HISTORY.md b/HISTORY.md index a70f3ca..4658f23 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -1,3 +1,7 @@ +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 }` diff --git a/README.md b/README.md index 59cb5da..d63c5e0 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ The global structure of `disconnect` looks as follows: ``` require('disconnect') -> new Client() -> oauth() - -> database() + -> database() -> marketplace() -> user() -> collection() -> wantlist() diff --git a/lib/client.js b/lib/client.js index d92bcc7..79df004 100644 --- a/lib/client.js +++ b/lib/client.js @@ -1,11 +1,11 @@ 'use strict'; var https = require('https'), - zlib = require('zlib'), - url = require('url'), - pkg = require('../package.json'), - error = require('./error.js'), - util = require('./util.js'); + zlib = require('zlib'), + url = require('url'), + pkg = require('../package.json'), + error = require('./error.js'), + util = require('./util.js'); module.exports = DiscogsClient; @@ -14,13 +14,14 @@ module.exports = DiscogsClient; */ var defaultConfig = { - host: 'api.discogs.com', - port: 443, - userAgent: 'DisConnectClient/'+pkg.version+' +'+pkg.homepage, - apiVersion: 'v2', - outputFormat: 'discogs', // Possible values: 'discogs' / 'plaintext' / 'html' - requestLimit: 240, // Maximum number of requests to the Discogs API per interval - requestLimitInterval: 60000 // Request interval in milliseconds + host: 'api.discogs.com', + port: 443, + userAgent: 'DisConnectClient/' + pkg.version + ' +' + pkg.homepage, + apiVersion: 'v2', + outputFormat: 'discogs', // Possible values: 'discogs' / 'plaintext' / 'html' + requestLimit: 25, // Maximum number of requests to the Discogs API per interval + requestLimitAuth: 60, // Maximum number of requests to the Discogs API per interval when authenticated + requestLimitInterval: 60000 // Request interval in milliseconds }; /** @@ -29,8 +30,8 @@ var defaultConfig = { */ var queue = require('./queue.js')({ - maxCalls: defaultConfig.requestLimit, - interval: defaultConfig.requestLimitInterval + maxCalls: defaultConfig.requestLimit, + interval: defaultConfig.requestLimitInterval }); /** @@ -40,33 +41,39 @@ var queue = require('./queue.js')({ * @return {DiscogsClient} */ -function DiscogsClient(userAgent, auth){ - // Allow the class to be called as a function, returning an instance - if(!(this instanceof DiscogsClient)){ +function DiscogsClient(userAgent, auth) { + // Allow the class to be called as a function, returning an instance + if (!(this instanceof DiscogsClient)) { return new DiscogsClient(userAgent, auth); - } - // Set the default configuration - this.config = util.merge({}, defaultConfig); - // Set the custom User Agent when provided - if(typeof userAgent === 'string'){ - this.config.userAgent = userAgent; - } - // No userAgent provided, but instead we have an accessObject - if((arguments.length === 1) && (typeof userAgent === 'object')){ auth = userAgent; } - // Set auth data when provided - if(auth && (typeof auth === 'object')){ - if(!auth.hasOwnProperty('method')){ - auth.method = 'discogs'; - } - if(!auth.hasOwnProperty('level')){ - if(auth.userToken){ - auth.level = 2; - }else if(auth.consumerKey && auth.consumerSecret){ - auth.level = 1; - } - } - this.auth = util.merge({}, auth); - } + } + // Set the default configuration + this.config = util.merge({}, defaultConfig); + // Set the custom User Agent when provided + if (typeof userAgent === 'string') { + this.config.userAgent = userAgent; + } + // No userAgent provided, but instead we have an accessObject + if ((arguments.length === 1) && (typeof userAgent === 'object')) { + auth = userAgent; + } + // Set auth data when provided + if (auth && (typeof auth === 'object')) { + queue.setConfig({maxCalls: this.config.requestLimitAuth}); + if (!auth.hasOwnProperty('method')) { + auth.method = 'discogs'; + } + if (!auth.hasOwnProperty('level')) { + if (auth.userToken) { + auth.level = 2; + } else if (auth.consumerKey && auth.consumerSecret) { + auth.level = 1; + } + } + this.auth = util.merge({}, auth); + // Unauthenticated new client instances will decrease the shared request limit + } else { + queue.setConfig({maxCalls: this.config.requestLimit}); + } } /** @@ -74,13 +81,13 @@ function DiscogsClient(userAgent, auth){ * @param {object} customConfig - Custom configuration object for Browserify/CORS/Proxy use cases * @return {DiscogsClient} */ -DiscogsClient.prototype.setConfig = function(customConfig){ - util.merge(this.config, customConfig); - queue.setConfig({ - maxCalls: this.config.requestLimit, - interval: this.config.requestLimitInterval - }); - return this; +DiscogsClient.prototype.setConfig = function(customConfig) { + util.merge(this.config, customConfig); + queue.setConfig({ + maxCalls: (this.authenticated() ? this.config.requestLimitAuth : this.config.requestLimit), + interval: this.config.requestLimitInterval + }); + return this; }; /** @@ -89,9 +96,9 @@ DiscogsClient.prototype.setConfig = function(customConfig){ * @return {boolean} */ -DiscogsClient.prototype.authenticated = function(level){ - level = level||0; - return (!(typeof this.auth === 'undefined') && (this.auth.level > 0) && (this.auth.level >= level)); +DiscogsClient.prototype.authenticated = function(level) { + level = level || 0; + return (!(typeof this.auth === 'undefined') && (this.auth.level > 0) && (this.auth.level >= level)); }; /** @@ -100,8 +107,8 @@ DiscogsClient.prototype.authenticated = function(level){ * @return {DiscogsClient|Promise} */ -DiscogsClient.prototype.getIdentity = function(callback){ - return this.get({url: '/oauth/identity', authLevel: 2}, callback); +DiscogsClient.prototype.getIdentity = function(callback) { + return this.get({url: '/oauth/identity', authLevel: 2}, callback); }; /** @@ -109,23 +116,23 @@ DiscogsClient.prototype.getIdentity = function(callback){ * @param {function} callback - Callback function receiving the data */ -DiscogsClient.prototype.about = function(callback){ - var clientInfo = { - version: pkg.version, - userAgent: this.config.userAgent, - authMethod: (this.auth ? this.auth.method : 'none'), - authLevel: (this.auth ? this.auth.level : 0) - }; - if(typeof callback === 'function'){ - return this.get('', function(err, data){ - data && (data.disconnect = clientInfo); - callback(err, data); - }); - } - return this.get('').then(function(data){ - data && (data.disconnect = clientInfo); - return data; - }); +DiscogsClient.prototype.about = function(callback) { + var clientInfo = { + version: pkg.version, + userAgent: this.config.userAgent, + authMethod: (this.auth ? this.auth.method : 'none'), + authLevel: (this.auth ? this.auth.level : 0) + }; + if (typeof callback === 'function') { + return this.get('', function(err, data) { + data && (data.disconnect = clientInfo); + callback(err, data); + }); + } + return this.get('').then(function(data) { + data && (data.disconnect = clientInfo); + return data; + }); }; /** @@ -140,102 +147,108 @@ DiscogsClient.prototype.about = function(callback){ * @return {DiscogsClient} */ -DiscogsClient.prototype._rawRequest = function(options, callback){ - var data = options.data||null, - method = options.method||'GET', - urlParts = url.parse(options.url), - encoding = options.encoding||'utf8'; - - // Build request headers - var headers = { - 'User-Agent': this.config.userAgent, - 'Accept': 'application/json,application/vnd.discogs.'+this.config.apiVersion+'.'+this.config.outputFormat+'+json,application/octet-stream', - 'Accept-Encoding': 'gzip,deflate', - 'Host': this.config.host, - 'Connection': 'close', - 'Content-Length': 0 - }; - - // Add content headers for POST/PUT requests that contain data - if(data){ - if(typeof data === 'object'){ data = JSON.stringify(data); } // Convert data to a JSON string when data is an object/array - headers['Content-Type'] = 'application/json'; // Discogs accepts data in JSON format - headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); - } - - // Add Authorization header when authenticated (or in the process of authenticating) - if(this.auth && (this.auth.consumerKey || this.auth.userToken)){ - var authHeader = ''; - if(this.auth.method === 'oauth'){ - var fullUrl = (urlParts.protocol && urlParts.host) ? urlParts.href : 'https://'+this.config.host+urlParts.path; - authHeader = this.oauth().toHeader(method, fullUrl); - }else if(this.auth.method === 'discogs'){ - authHeader = 'Discogs'; - if(this.auth.userToken){ - authHeader += ' token='+this.auth.userToken; - }else if(this.auth.consumerKey){ - authHeader += ' key='+this.auth.consumerKey+', secret='+this.auth.consumerSecret; - } - } - headers['Authorization'] = authHeader; - } - - // Set the HTTPS request options - var requestOptions = { - host: urlParts.host||this.config.host, - port: urlParts.port||this.config.port, - path: urlParts.path, - method: method, - headers: headers - }; - - // Build the HTTPS request - var req = https.request(requestOptions, function(res){ - var data = '', rateLimit = null, add = function(chunk){ data += chunk.toString(); }; - - // Pass the data to the callback and pass an error on unsuccessful HTTP status - var passData = function(){ - var err = null, status = parseInt(res.statusCode, 10); - if(status > 399){ // Unsuccessful HTTP status? Then pass an error to the callback - var match = data.match(/^\{"message": "(.+)"\}/i); - err = new error.DiscogsError(status, ((match&&match[1]) ? match[1] : null)); - } - callback(err, data, rateLimit); - }; - - // Find and add rate limiting when present - if(res.headers['x-discogs-ratelimit']){ - rateLimit = { - limit: parseInt(res.headers['x-discogs-ratelimit'], 10), - used: parseInt(res.headers['x-discogs-ratelimit-used'], 10), - remaining: parseInt(res.headers['x-discogs-ratelimit-remaining'], 10) - }; - } - - // Get the response content and pass it to the callback - switch(res.headers['content-encoding']){ - case 'gzip': - var gunzip = zlib.createGunzip().on('data', add).on('end', passData); - res.pipe(gunzip); - break; - case 'deflate': - var inflate = zlib.createInflate().on('data', add).on('end', passData); - res.pipe(inflate); - break; - default: - // Set encoding when provided - res.setEncoding(encoding); - res.on('data', add).on('end', passData); - } - }).on('error', function(err){ - callback(err); - }); - - // When present, write the data to the request - if(data){ req.write(data); } - - req.end(); - return this; +DiscogsClient.prototype._rawRequest = function(options, callback) { + var data = options.data || null, + method = options.method || 'GET', + urlParts = url.parse(options.url), + encoding = options.encoding || 'utf8'; + + // Build request headers + var headers = { + 'User-Agent': this.config.userAgent, + 'Accept': 'application/json,application/vnd.discogs.' + this.config.apiVersion + '.' + this.config.outputFormat + '+json,application/octet-stream', + 'Accept-Encoding': 'gzip,deflate', + 'Host': this.config.host, + 'Connection': 'close', + 'Content-Length': 0 + }; + + // Add content headers for POST/PUT requests that contain data + if (data) { + if (typeof data === 'object') { + data = JSON.stringify(data); + } // Convert data to a JSON string when data is an object/array + headers['Content-Type'] = 'application/json'; // Discogs accepts data in JSON format + headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); + } + + // Add Authorization header when authenticated (or in the process of authenticating) + if (this.auth && (this.auth.consumerKey || this.auth.userToken)) { + var authHeader = ''; + if (this.auth.method === 'oauth') { + var fullUrl = (urlParts.protocol && urlParts.host) ? urlParts.href : 'https://' + this.config.host + urlParts.path; + authHeader = this.oauth().toHeader(method, fullUrl); + } else if (this.auth.method === 'discogs') { + authHeader = 'Discogs'; + if (this.auth.userToken) { + authHeader += ' token=' + this.auth.userToken; + } else if (this.auth.consumerKey) { + authHeader += ' key=' + this.auth.consumerKey + ', secret=' + this.auth.consumerSecret; + } + } + headers['Authorization'] = authHeader; + } + + // Set the HTTPS request options + var requestOptions = { + host: urlParts.host || this.config.host, + port: urlParts.port || this.config.port, + path: urlParts.path, + method: method, + headers: headers + }; + + // Build the HTTPS request + var req = https.request(requestOptions, function(res) { + var data = '', rateLimit = null, add = function(chunk) { + data += chunk.toString(); + }; + + // Pass the data to the callback and pass an error on unsuccessful HTTP status + var passData = function() { + var err = null, status = parseInt(res.statusCode, 10); + if (status > 399) { // Unsuccessful HTTP status? Then pass an error to the callback + var match = data.match(/^\{"message": "(.+)"\}/i); + err = new error.DiscogsError(status, ((match && match[1]) ? match[1] : null)); + } + callback(err, data, rateLimit); + }; + + // Find and add rate limiting when present + if (res.headers['x-discogs-ratelimit']) { + rateLimit = { + limit: parseInt(res.headers['x-discogs-ratelimit'], 10), + used: parseInt(res.headers['x-discogs-ratelimit-used'], 10), + remaining: parseInt(res.headers['x-discogs-ratelimit-remaining'], 10) + }; + } + + // Get the response content and pass it to the callback + switch (res.headers['content-encoding']) { + case 'gzip': + var gunzip = zlib.createGunzip().on('data', add).on('end', passData); + res.pipe(gunzip); + break; + case 'deflate': + var inflate = zlib.createInflate().on('data', add).on('end', passData); + res.pipe(inflate); + break; + default: + // Set encoding when provided + res.setEncoding(encoding); + res.on('data', add).on('end', passData); + } + }).on('error', function(err) { + callback(err); + }); + + // When present, write the data to the request + if (data) { + req.write(data); + } + + req.end(); + return this; }; /** @@ -250,55 +263,55 @@ DiscogsClient.prototype._rawRequest = function(options, callback){ * @return {DiscogsClient|Promise} */ -DiscogsClient.prototype._request = function(options, callback){ - var client = this, - doRequest = function(){ - client._rawRequest(options, function(err, data, rateLimit){ - if(data && options.json && (data.indexOf(' 5) ? 5 : rating)}, callback); - } - }; - - /** - * Get master release data - * @param {(number|string)} master - The Discogs master release ID - * @param {function} [callback] - Callback function - * @return {DiscogsClient|Promise} - */ - - database.getMaster = function(master, callback){ - return client.get('/masters/'+master, callback); - }; - - /** - * Get the release versions contained in the given master release - * @param {(number|string)} master - The Discogs master release ID - * @param {object} [params] - optional pagination params - * @param {function} [callback] - Callback function - * @return {DiscogsClient|Promise} - */ - - database.getMasterVersions = function(master, params, callback){ - var path = '/masters/'+master+'/versions'; - if((arguments.length === 2) && (typeof params === 'function')){ - callback = params; - }else{ - path = util.addParams(path, params); - } - return client.get(path, callback); - }; - - /** - * Get label data - * @param {(number|string)} label - The Discogs label ID - * @param {function} [callback] - Callback function - * @return {DiscogsClient|Promise} - */ - - database.getLabel = function(label, callback){ - return client.get('/labels/'+label, callback); - }; - - /** - * Get label release data - * @param {(number|string)} label - The Discogs label ID - * @param {object} [params] - Optional pagination params - * @param {function} [callback] - Callback function - * @return {DiscogsClient|Promise} - */ - - database.getLabelReleases = function(label, params, callback){ - var path = '/labels/'+label+'/releases'; - if((arguments.length === 2) && (typeof params === 'function')){ - callback = params; - }else{ - path = util.addParams(path, params); - } - return client.get(path, callback); - }; - - /** - * Get an image - * @param {string} url - The full image url - * @param {function} [callback] - Callback function - * @return {DiscogsClient|Promise} - */ - - database.getImage = function(url, callback){ - return client.get({url: url, encoding: 'binary', queue: false, json: false}, callback); - }; - - /** - * Search the database - * @param {string} query - The search query - * @param {object} [params] - Search parameters as defined on http://www.discogs.com/developers/#page:database,header:database-search - * @param {function} [callback] - Callback function - * @return {DiscogsClient|Promise} - */ - - database.search = function(query, params, callback){ - var obj = {}; - if((arguments.length === 2) && (typeof params === 'function')){ - callback = params; - } - if(typeof params === 'object'){ - obj = params; - } else if (typeof query === 'object') { - obj = query; - } - obj.q = typeof query === 'string' ? query : ''; - return client.get({url: util.addParams('/database/search', obj), authLevel: 1}, callback); }; - - return database; +module.exports = function(client) { + var database = {}; + + /** + * Expose Discogs database status constants + */ + + database.status = {accepted: 'Accepted', draft: 'Draft', deleted: 'Deleted', rejected: 'Rejected'}; + + /** + * Get artist data + * @param {(number|string)} artist - The Discogs artist ID + * @param {object} [options] - Show releases by the artist + pagination params + * @param {function} [callback] - Callback function + * @return {DiscogsClient|Promise} + */ + + database.getArtist = function(artist, callback) { + return client.get('/artists/' + artist, callback); + }; + + /** + * Get artist release data + * @param {(number|string)} artist - The Discogs artist ID + * @param {object} [params] - Optional pagination params + * @param {function} [callback] - Callback function + * @return {DiscogsClient|Promise} + */ + + database.getArtistReleases = function(artist, params, callback) { + var path = '/artists/' + artist + '/releases'; + if ((arguments.length === 2) && (typeof params === 'function')) { + callback = params; + } else { + path = util.addParams(path, params); + } + return client.get(path, callback); + }; + + /** + * Get release data + * @param {(number|string)} release - The Discogs release ID + * @param {function} [callback] - Callback + * @return {DiscogsClient|Promise} + */ + + database.getRelease = function(release, callback) { + return client.get('/releases/' + release, callback); + }; + + /** + * Get the release rating for the given user + * @param {(number|string)} release - The Discogs release ID + * @param {string} user - The Discogs user name + * @param {function} [callback] - Callback function + * @return {DiscogsClient|Promise} + */ + + database.getReleaseRating = function(release, user, callback) { + return client.get('/releases/' + release + '/rating/' + util.escape(user), callback); + }; + + /** + * Set (or remove) a release rating for the given logged in user + * @param {(number|string)} release - The Discogs release ID + * @param {string} user - The Discogs user name + * @param {number} rating - The new rating for a release between 1 and 5. Null = remove rating + * @param {function} [callback] - Callback function + * @return {DiscogsClient|Promise} + */ + + database.setReleaseRating = function(release, user, rating, callback) { + var url = '/releases/' + release + '/rating/' + util.escape(user); + if (!rating) { + return client.delete({url: url, authLevel: 2}, callback); + } else { + return client.put({url: url, authLevel: 2}, {rating: ((rating > 5) ? 5 : rating)}, callback); + } + }; + + /** + * Get master release data + * @param {(number|string)} master - The Discogs master release ID + * @param {function} [callback] - Callback function + * @return {DiscogsClient|Promise} + */ + + database.getMaster = function(master, callback) { + return client.get('/masters/' + master, callback); + }; + + /** + * Get the release versions contained in the given master release + * @param {(number|string)} master - The Discogs master release ID + * @param {object} [params] - optional pagination params + * @param {function} [callback] - Callback function + * @return {DiscogsClient|Promise} + */ + + database.getMasterVersions = function(master, params, callback) { + var path = '/masters/' + master + '/versions'; + if ((arguments.length === 2) && (typeof params === 'function')) { + callback = params; + } else { + path = util.addParams(path, params); + } + return client.get(path, callback); + }; + + /** + * Get label data + * @param {(number|string)} label - The Discogs label ID + * @param {function} [callback] - Callback function + * @return {DiscogsClient|Promise} + */ + + database.getLabel = function(label, callback) { + return client.get('/labels/' + label, callback); + }; + + /** + * Get label release data + * @param {(number|string)} label - The Discogs label ID + * @param {object} [params] - Optional pagination params + * @param {function} [callback] - Callback function + * @return {DiscogsClient|Promise} + */ + + database.getLabelReleases = function(label, params, callback) { + var path = '/labels/' + label + '/releases'; + if ((arguments.length === 2) && (typeof params === 'function')) { + callback = params; + } else { + path = util.addParams(path, params); + } + return client.get(path, callback); + }; + + /** + * Get an image + * @param {string} url - The full image url + * @param {function} [callback] - Callback function + * @return {DiscogsClient|Promise} + */ + + database.getImage = function(url, callback) { + return client.get({url: url, encoding: 'binary', queue: false, json: false}, callback); + }; + + /** + * Search the database + * @param {string} query - The search query + * @param {object} [params] - Search parameters as defined on http://www.discogs.com/developers/#page:database,header:database-search + * @param {function} [callback] - Callback function + * @return {DiscogsClient|Promise} + */ + + database.search = function(query, params, callback) { + var obj = {}; + if ((arguments.length === 2) && (typeof params === 'function')) { + callback = params; + } + if (typeof params === 'object') { + obj = params; + } else if (typeof query === 'object') { + obj = query; + } + if (typeof query === 'string') { + obj.q = query; + } + return client.get({url: util.addParams('/database/search', obj), authLevel: 1}, callback); + }; + + return database; }; \ No newline at end of file diff --git a/test/all.js b/test/all.js index 777ed4e..fbe33a3 100644 --- a/test/all.js +++ b/test/all.js @@ -1,6 +1,6 @@ var wru = require('wru'), tests = [], - files = ['error','queue','util','client']; + files = ['error','queue','util','client','database']; for(var i in files){ tests = tests.concat(require('./'+files[i]+'.js')); diff --git a/test/client.js b/test/client.js index 1bbd4f4..4060ec2 100644 --- a/test/client.js +++ b/test/client.js @@ -1,100 +1,57 @@ var wru = require('wru'), - nock = require('nock'), - DiscogsClient = require('../lib/client.js'); + nock = require('nock'), + DiscogsClient = require('../lib/client.js'); var tests = module.exports = [ - { - name: 'DiscogsClient: Test instance', - test: function(){ - wru.assert('Instance of DiscogsClient', (new DiscogsClient() instanceof DiscogsClient)); - } - },{ - name: 'DiscogsClient: Test authenticated()', - test: function(){ - wru.assert('Authentication level 1 === false', (new DiscogsClient().authenticated(1) === false)); - } - },{ - name: 'DiscogsClient: Test get()', - test: function(){ - var client = new DiscogsClient(); - client.get({url: '/labels/1'}, wru.async(function(err, data){ - wru.assert('No error', !err); - wru.assert('Correct response data', (data && (data.id === 1))); - })); - } - },{ - name: 'DiscogsClient: Test Promise', - test: function(){ - var client = new DiscogsClient(); - var promise = client.about(); - var isPromise = (typeof promise.then === 'function'); - wru.assert('Returns Promise', isPromise); - if(isPromise){ - promise.then(wru.async(function(data){ - wru.assert('Promis resolved', (typeof data.disconnect !== 'undefined')); - })); - } - } - },{ - name: 'DiscogsClient: Test custom configuration', - test: function(){ - nock('https://www.example.com').get('/labels/1').reply(200, '{"result": "success"}'); - - var client = new DiscogsClient().setConfig({host: 'www.example.com'}); - client.get({url: '/labels/1'}, wru.async(function(err, data){ - wru.assert('No error', !err); - wru.assert('Correct response data', (data && data.result === 'success')); - })); - }, - teardown: function(){ - nock.cleanAll(); - } - },{ - name: 'DiscogsClient: Test search without query but with params', - test: function(){ - nock('https://www.example.com').get('/database/search?artist=X&title=Y&q=').reply(200, '{"result": "success"}'); + { + name: 'DiscogsClient: Test instance', + test: function(){ + wru.assert('Instance of DiscogsClient', (new DiscogsClient() instanceof DiscogsClient)); + } + },{ + name: 'DiscogsClient: Test authenticated()', + test: function(){ + wru.assert('Authentication level 1 === false', (new DiscogsClient().authenticated(1) === false)); + } + },{ + name: 'DiscogsClient: Test get()', + test: function(){ + var client = new DiscogsClient(); + client.get({url: '/labels/1'}, wru.async(function(err, data){ + wru.assert('No error', !err); + wru.assert('Correct response data', (data && (data.id === 1))); + })); + } + },{ + name: 'DiscogsClient: Test Promise', + test: function(){ + var client = new DiscogsClient(); + var promise = client.about(); + var isPromise = (typeof promise.then === 'function'); + wru.assert('Returns Promise', isPromise); + if(isPromise){ + promise.then(wru.async(function(data){ + wru.assert('Promis resolved', (typeof data.disconnect !== 'undefined')); + })); + } + } + },{ + name: 'DiscogsClient: Test custom configuration', + test: function(){ + nock('https://www.example.com').get('/labels/1').reply(200, '{"result": "success"}'); - var client = new DiscogsClient('agent', {consumerKey: 'u', consumerSecret: 'p'}).setConfig({host: 'www.example.com'}); - var db = client.database(); - db.search({artist: 'X', title: 'Y'}, wru.async(function(err, data){ - wru.assert('No error', !err); - wru.assert('Correct response data', (data && data.result === 'success')); - })); - }, - teardown: function(){ - nock.cleanAll(); - } - },{ - name: 'DiscogsClient: Test search with query and params', - test: function(){ - nock('https://www.example.com').get('/database/search?artist=X&title=Y&q=somequery').reply(200, '{"result": "success"}'); - - var client = new DiscogsClient('agent', {consumerKey: 'u', consumerSecret: 'p'}).setConfig({host: 'www.example.com'}); - var db = client.database(); - db.search('somequery', {artist: 'X', title: 'Y'}, wru.async(function(err, data){ - wru.assert('No error', !err); - wru.assert('Correct response data', (data && data.result === 'success')); - })); - }, - teardown: function(){ - nock.cleanAll(); - } - },{ - name: 'DiscogsClient: Test search with query only', - test: function(){ - nock('https://www.example.com').get('/database/search?q=somequery').reply(200, '{"result": "success"}'); - - var client = new DiscogsClient('agent', {consumerKey: 'u', consumerSecret: 'p'}).setConfig({host: 'www.example.com'}); - var db = client.database(); - db.search('somequery', wru.async(function(err, data){ - wru.assert('No error', !err); - wru.assert('Correct response data', (data && data.result === 'success')); - })); - }, - teardown: function(){ - nock.cleanAll(); - } - } + var client = new DiscogsClient().setConfig({host: 'www.example.com'}); + client.get({url: '/labels/1'}, wru.async(function(err, data){ + wru.assert('No error', !err); + wru.assert('Correct response data', (data && data.result === 'success')); + })); + }, + teardown: function(){ + nock.cleanAll(); + } + } ]; -if(!module.parent){ wru.test(tests); } \ No newline at end of file +if(!module.parent){ + wru.test(tests); +} \ No newline at end of file diff --git a/test/database.js b/test/database.js new file mode 100644 index 0000000..e8fc142 --- /dev/null +++ b/test/database.js @@ -0,0 +1,56 @@ +var wru = require('wru'), + nock = require('nock'), + DiscogsClient = require('../lib/client.js'); + +var tests = module.exports = [ + { + name: 'Database: Test search without query but with params', + test: function(){ + nock('https://api.discogs.com').get('/database/search?artist=X&title=Y').reply(200, '{"result": "success"}'); + + var client = new DiscogsClient('agent', {consumerKey: 'u', consumerSecret: 'p'}); + var db = client.database(); + db.search({artist: 'X', title: 'Y'}, wru.async(function(err, data){ + wru.assert('No error', !err); + wru.assert('Correct response data', (data && data.result === 'success')); + })); + }, + teardown: function(){ + nock.cleanAll(); + } + },{ + name: 'Database: Test search with query and params', + test: function() { + nock('https://api.discogs.com').get('/database/search?artist=X&title=Y&q=somequery').reply(200, '{"result": "success"}'); + + var client = new DiscogsClient('agent', {consumerKey: 'u', consumerSecret: 'p'}); + var db = client.database(); + db.search('somequery', {artist: 'X', title: 'Y'}, wru.async(function(err, data){ + wru.assert('No error', !err); + wru.assert('Correct response data', (data && data.result === 'success')); + })); + }, + teardown: function(){ + nock.cleanAll(); + } + },{ + name: 'Database: Test search with query only', + test: function() { + nock('https://api.discogs.com').get('/database/search?q=somequery').reply(200, '{"result": "success"}'); + + var client = new DiscogsClient('agent', {consumerKey: 'u', consumerSecret: 'p'}); + var db = client.database(); + db.search('somequery', wru.async(function(err, data){ + wru.assert('No error', !err); + wru.assert('Correct response data', (data && data.result === 'success')); + })); + }, + teardown: function(){ + nock.cleanAll(); + } + } +]; + +if(!module.parent){ + wru.test(tests); +} \ No newline at end of file