-
-
Notifications
You must be signed in to change notification settings - Fork 74
/
index.js
86 lines (68 loc) · 1.62 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
'use strict';
const qs = require('querystring');
const got = require('got');
class Client {
constructor(id, apiKey) {
if (!id) {
throw new TypeError('Expected a Custom Search Engine ID');
}
if (!apiKey) {
throw new TypeError('Expected an API key');
}
this.endpoint = 'https://www.googleapis.com';
this.apiKey = apiKey;
this.id = id;
}
search(query, options) {
if (!query) {
throw new TypeError('Expected a query');
}
const url = `${this.endpoint}/customsearch/v1?${this.buildQuery(query, options)}`;
return got(url, {json: true}).then(res => {
const items = res.body.items || [];
return items.map(item => ({
type: item.mime,
width: item.image.width,
height: item.image.height,
size: item.image.byteSize,
url: item.link,
thumbnail: {
url: item.image.thumbnailLink,
width: item.image.thumbnailWidth,
height: item.image.thumbnailHeight
},
description: item.snippet,
parentPage: item.image.contextLink
}));
});
}
buildQuery(query, options) {
options = options || {};
const result = {
q: query.replace(/\s/g, '+'),
searchType: 'image',
cx: this.id,
key: this.apiKey
};
if (options.page) {
result.start = options.page;
}
if (options.size) {
result.imgSize = options.size;
}
if (options.type) {
result.imgType = options.type;
}
if (options.dominantColor) {
result.imgDominantColor = options.dominantColor;
}
if (options.colorType) {
result.imgColorType = options.colorType;
}
if (options.safe) {
result.safe = options.safe;
}
return qs.stringify(result);
}
}
module.exports = Client;