-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
67 lines (56 loc) · 1.99 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
'use strict';
var https = require('https');
require('dotenv').config();
/**
* Retrieves a list of image search results from Google
* @param (String) searchTerm
* @param (Function) callback (function to call once results are processed)
* @param (Number) -optional- start (starting from what result)
* @param (Number) -optional- num (how many results to return, 1 - 10)
*
* @return (Object)
*
*/
function getImageSearchResults(searchTerm, callback, start, num) {
start = start < 0 || start > 90 || typeof(start) === 'undefined' ? 0 : start;
num = num < 1 || num > 10 || typeof(num) === 'undefined' ? 10 : num;
if (!searchTerm) {
console.error('No search term');
}
var parameters = '&q=' + encodeURIComponent(searchTerm);
parameters += '&searchType=image';
parameters += start ? '&start=' + start : '';
parameters += '&num=' + num;
var options = {
host: 'www.googleapis.com',
path: '/customsearch/v1?key=' + process.env.CSE_API_KEY + '&cx=' + process.env.CSE_ID + parameters
};
var result = '';
https.get(options, function(response) {
response.setEncoding('utf8');
response.on('data', function(data) {
result += data;
});
response.on('end', function () {
var data = JSON.parse(result);
var resultsArray = [];
// check for usage limits (contributed by @ryanmete)
// This handles the exception thrown when a user's Google CSE quota has been exceeded for the day.
// Google CSE returns a JSON object with a field called "error" if quota is exceed.
if(data.error && data.error.errors) {
resultsArray.push(data.error.errors[0]);
// returns the JSON formatted error message in the callback
callback(resultsArray);
} else if(data.items) {
// search returned results
data.items.forEach(function (item) {
resultsArray.push(item);
});
callback(resultsArray);
} else {
callback([]);
}
});
});
}
module.exports = getImageSearchResults;