-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
67 lines (53 loc) · 1.46 KB
/
index.ts
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
import { HASDATA_API_URL, HASDATA_API_ENDPOINT } from './const';
import { doRequest } from './utils';
import path from 'path';
import * as hdType from './types';
class GoogleSerpApi {
constructor(private apiKey: string) {
if (!this.apiKey) {
throw new Error('API Key is not provided');
}
if (!HASDATA_API_URL) {
throw new Error('API URL is not provided');
}
if (!HASDATA_API_ENDPOINT) {
throw new Error('API Endpoint is not provided');
}
}
private formatResponse(responseBody: any): any {
let result: any;
try {
result = JSON.parse(responseBody);
} catch {
result = responseBody;
}
if (result.status === 'ok') {
return result.scrapingResult
}
if (result.error) {
throw new Error(result.error)
}
if (result.status === 'error') {
throw new Error(`${result.message}: ${JSON.stringify(result.errors || {}) }`);
}
return result
}
public async getSearchResults(params: hdType.GetSearchResultsParams): Promise<any> {
const url = path.join(HASDATA_API_URL, HASDATA_API_ENDPOINT, '/');
const responseBody = await doRequest(
`${url}`,
{
'x-api-key': this.apiKey,
},
{
...params,
source: 'nodejs_sdk',
}
);
return this.formatResponse(responseBody);
}
public scrape(params: hdType.GetSearchResultsParams): Promise<any> {
return this.getSearchResults(params);
}
}
export = GoogleSerpApi;