84 lines
2.8 KiB
JavaScript
84 lines
2.8 KiB
JavaScript
(function() {
|
|
var Promise, getUrl, request,
|
|
indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
|
|
|
|
request = require('request');
|
|
|
|
Promise = require('bluebird');
|
|
|
|
getUrl = function(object) {
|
|
return object.unescapedUrl;
|
|
};
|
|
|
|
module.exports = function(searchTerm, options) {
|
|
return new Promise((function(_this) {
|
|
return function(resolve, reject) {
|
|
|
|
/*
|
|
To keep it simple, options is not a needed input.
|
|
That means that it is possible for only 2 inputs to
|
|
be passed, which would mean that options was the callback,
|
|
so make the 2nd input the callback and reset options.
|
|
*/
|
|
var color, language, limit, possibleColors, ref, rights, safety, searchPrefix, searchUrl, size;
|
|
if (options == null) {
|
|
options = {};
|
|
}
|
|
options.safe = options.safe || "moderate";
|
|
options.size = options.size || "any";
|
|
options.color = options.color || "any";
|
|
options.language = options.language || "en";
|
|
options.limit = options.limit || 5;
|
|
options.rights = options.rights || "";
|
|
switch (options.safe) {
|
|
case true:
|
|
safety = "active";
|
|
break;
|
|
case false:
|
|
safety = "off";
|
|
break;
|
|
default:
|
|
safety = options.safe;
|
|
}
|
|
switch (options.size) {
|
|
case "small":
|
|
size = "icon";
|
|
break;
|
|
case "medium":
|
|
size = "media";
|
|
break;
|
|
case "large":
|
|
size = "xxlarge";
|
|
break;
|
|
case "huge":
|
|
size = "huge";
|
|
break;
|
|
default:
|
|
size = "any";
|
|
}
|
|
possibleColors = ["black", "blue", "brown", "gray", "green", "orange", "pink", "purple", "red", "teal", "white", "yellow"];
|
|
if (ref = options.color, indexOf.call(possibleColors, ref) >= 0) {
|
|
color = options.color;
|
|
} else {
|
|
"any";
|
|
}
|
|
language = options.language.substring(0, 1).toLowerCase();
|
|
limit = options.limit;
|
|
rights = options.rights;
|
|
searchPrefix = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0";
|
|
searchUrl = searchPrefix + "&q=" + searchTerm + "&as_rights=" + rights + "&imgsz=" + size + "&safe=" + safety + "&hl=" + language + "&imgcolor=" + color + "&rsz=" + limit;
|
|
return request(searchUrl, function(error, response, body) {
|
|
var images, parsed, urls;
|
|
parsed = JSON.parse(body);
|
|
if (parsed.responseData == null) {
|
|
return resolve([]);
|
|
}
|
|
images = parsed.responseData.results;
|
|
urls = images.map(getUrl);
|
|
return resolve(urls);
|
|
});
|
|
};
|
|
})(this));
|
|
};
|
|
|
|
}).call(this);
|