This repository was archived by the owner on May 8, 2025. It is now read-only.
forked from vadimdemedes/google-images
-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
68 lines (54 loc) · 1.61 KB
/
index.js
File metadata and controls
68 lines (54 loc) · 1.61 KB
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
import axios from "axios";
export default 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;
}
async search(query, options) {
try {
if (!query) {
throw new TypeError("Expected a query");
}
const url = `${this.endpoint}/customsearch/v1?${this.buildQuery(query, options)}`;
const result = await axios.get(url);
return result.data.items;
} catch (error) {
return error.response.data.error.message;
}
}
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 new URLSearchParams(result).toString();
}
}