New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement search #46

Merged
merged 4 commits into from Dec 25, 2017
Merged
Diff settings

Always

Just for now

Copy path View file
@@ -185,6 +185,28 @@ imgur.uploadFile('~/*.(jpg|png|gif)')
console.error(err.message);
});
```
#### Searching images within the gallery:
The first argument should be a query to search and it's the only required option. The second argument is optional params to sort your query by.
- `sort` - Accepts 'time', 'viral', or 'top' as a value. Defaults to top.
- `dateRange` - Accepts 'day', 'week', 'month', 'year', or 'all' as a value. Defaults to all.
- `page` - Accepts an integer (e.g. 1, 2, 3, 4) as a value. Defaults to 1.
Search returns an object with the query response as an array of objects that include an image's ID, title, description, views, etc.. and the params you sent with the request.
```javascript
var query = 'cats';
var optionalParams = {sort: 'top', dateRange: 'week', page: 1}
imgur.search(query, optionalParams)
.then(function(json) {
console.log(json);
})
.catch(function (err) {
console.error(err);
});
```
#### Fetching image data:
Copy path View file
@@ -44,8 +44,7 @@ imgur._imgurRequest = function (operation, payload, extraFormParams) {
json: true
};

if (!operation || typeof operation !== 'string' || (!payload && operation !== 'credits')) {
deferred.reject(new Error('Invalid argument'));
if (!operation || typeof operation !== 'string' || ( !payload && operation !== ('credits' && 'search') ) ) {
return deferred.promise;
}

@@ -74,6 +73,10 @@ imgur._imgurRequest = function (operation, payload, extraFormParams) {
options.method = 'DELETE';
options.uri += 'image/' + payload;
break;
case 'search':
options.method = 'GET';
options.uri += '/gallery/search/' + payload
break;
default:
deferred.reject(new Error('Invalid operation'));
return deferred.promise;
@@ -419,6 +422,63 @@ imgur.getAlbumInfo = function (id) {
return deferred.promise;
}

imgur.search = function(query, options) {
var deferred = Q.defer();
var checkQuery = imgur.checkQuery(query)
var params;
options = options || {}
if(checkQuery.constructor === Error) {
deferred.reject(checkQuery)
}
else {
var params = imgur.initSearchParams(query, options);
imgur._imgurRequest('search', params.queryStr)
.then(function (json) {
var copyOfParams = params
delete copyOfParams['queryStr']
deferred.resolve({data: json.data, params: copyOfParams});
})
.catch(function (err) {
deferred.reject(err);
});
}

return deferred.promise
}

imgur.checkQuery = function(query) {
var errMsg;
if(!query) {
errMsg = new Error("Search requires a query. Try searching with a query (e.g cats).")
}
else if(typeof query != 'string') {
errMsg = new Error("You did not pass a string as a query.")
}
else {
errMsg = ''
}
return errMsg
}


imgur.initSearchParams = function(query, options) {
var params = {sort: 'time', dateRange: 'all', page: '1'};

for(var key in options) {
if ( key == 'sort' || key == 'dateRange' || key == 'page' ) {
params[key] = params[key] != options[key] ? options[key] : params[key]
}
}

var queryStr = "";
Object.keys(params).forEach(function(param) {
queryStr += '/' + params[param];
})
queryStr += "?q=" + query;
params['queryStr'] = queryStr
return params
}


/**
* Upload an image file
@@ -598,6 +658,7 @@ imgur.uploadImages = function (images, uploadType, albumId) {
}



/**
* Get current credit limits
* @returns {promise}
Copy path View file
@@ -0,0 +1,69 @@
var imgur = require('../lib/imgur.js'),
chai = require('chai'),
chaiAsPromised = require('chai-as-promised'),
expect = chai.expect,
Q = require('q'),
sinon = require('sinon'),
sinonChai = require("sinon-chai")

chai.use(sinonChai);
chai.use(chaiAsPromised);

describe('SEARCH', function() {

describe('search options validations', function() {

it('should fail when query is not passed', function(done) {
var errMsg = "Search requires a query. Try searching with a query (e.g cats)."
expect(imgur.search()).to.be.rejectedWith(errMsg).and.notify(done)
})

it('should fail when query is passed a boolean', function(done) {
var errMsg = "You did not pass a string as a query."
expect(imgur.search(true)).to.be.rejectedWith(errMsg).and.notify(done)
})

it('should fail when query is passed a number', function(done) {
var errMsg = "You did not pass a string as a query."
expect(imgur.search(1)).to.be.rejectedWith(errMsg).and.notify(done)
})

it('should fail when query is passed a number', function(done) {
var errMsg = "You did not pass a string as a query."
expect(imgur.search(1)).to.be.rejectedWith(errMsg).and.notify(done)
})
})



describe('delegates to #_imgurRequest(\'search\', ...)', function() {
var mockResult = {
"data": [],
"params": {
"page": "1",
"dateRange": "month",
"sort": "viral"
}
};
var payload = "/viral/month/1?q=meme";

beforeEach(function() {
var deferred = Q.defer();
sinon.stub(imgur, "_imgurRequest").returns(deferred.promise);
deferred.resolve(mockResult);
});

afterEach(function () {
imgur._imgurRequest.restore();
});

it('should delegate', function(done) {
var promise = imgur.search('meme', {sort: "viral", dateRange: 'month', page: '1'});

expect(imgur._imgurRequest)
.to.have.been.calledWith('search', payload)
expect(promise)
.to.eventually.deep.equal(mockResult).and.notify(done)
});
});
})
ProTip! Use n and p to navigate between commits in a pull request.