@shaivpidadi/trends-js 0.0.0-beta.6 → 0.0.0-beta.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +183 -38
- package/dist/cjs/constants.d.ts +3 -0
- package/{lib → dist/cjs}/constants.js +19 -4
- package/{lib → dist/cjs}/helpers/googleTrendsAPI.d.ts +4 -1
- package/dist/cjs/helpers/googleTrendsAPI.js +339 -0
- package/{lib → dist/cjs}/helpers/request.d.ts +1 -1
- package/{lib → dist/cjs}/helpers/request.js +14 -18
- package/dist/cjs/index.d.ts +19 -0
- package/dist/cjs/index.js +24 -0
- package/dist/cjs/types/enums.d.ts +14 -0
- package/dist/cjs/types/enums.js +19 -0
- package/dist/esm/constants.d.ts +3 -0
- package/dist/esm/constants.js +50 -0
- package/dist/esm/errors/GoogleTrendsError.d.ts +23 -0
- package/dist/esm/errors/GoogleTrendsError.js +37 -0
- package/dist/esm/helpers/format.d.ts +2 -0
- package/dist/esm/helpers/format.js +76 -0
- package/dist/esm/helpers/googleTrendsAPI.d.ts +29 -0
- package/dist/esm/helpers/googleTrendsAPI.js +335 -0
- package/dist/esm/helpers/request.d.ts +9 -0
- package/dist/esm/helpers/request.js +75 -0
- package/dist/esm/index.d.ts +19 -0
- package/dist/esm/index.js +21 -0
- package/dist/esm/types/enums.d.ts +14 -0
- package/dist/esm/types/enums.js +16 -0
- package/package.json +29 -35
- package/lib/constants.d.ts +0 -2
- package/lib/helpers/googleTrendsAPI.js +0 -211
- package/lib/index.d.ts +0 -2
- package/lib/index.js +0 -7
- /package/{lib → dist/cjs}/errors/GoogleTrendsError.d.ts +0 -0
- /package/{lib → dist/cjs}/errors/GoogleTrendsError.js +0 -0
- /package/{lib → dist/cjs}/helpers/format.d.ts +0 -0
- /package/{lib → dist/cjs}/helpers/format.js +0 -0
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { ParseError } from '../errors/GoogleTrendsError';
|
|
2
|
+
// For future refrence and update: from google trends page rpc call response,
|
|
3
|
+
// 0 "twitter down" The main trending search term.
|
|
4
|
+
// 1 null Unused (reserved for future Google Trends data).
|
|
5
|
+
// 2 "US" Country code (where the trend is happening).
|
|
6
|
+
// 3 [1741599600] Unix timestamp (represents when the search started trending).
|
|
7
|
+
// 4 null Unused (reserved for future data).
|
|
8
|
+
// 5 null Unused (reserved for future data).
|
|
9
|
+
// 6 500000 Search volume index (estimated search interest for the term).
|
|
10
|
+
// 7 null Unused (reserved for future data).
|
|
11
|
+
// 8 1000 Trend ranking score (higher means more popular).
|
|
12
|
+
// 9 ["twitter down", "is twitter down", "is x down", ...] Related searches (other queries that users searched alongside this term).
|
|
13
|
+
// 10 [11] Unclear, possibly a category identifier.
|
|
14
|
+
// 11 [[3606769742, "en", "US"], [3596035008, "en", "US"]] User demographics or trending sources, with numerical IDs, language ("en" for English), and country ("US" for United States).
|
|
15
|
+
// 12 "twitter down" The original trending keyword (sometimes a duplicate of index 0).
|
|
16
|
+
export const extractJsonFromResponse = (text) => {
|
|
17
|
+
const cleanedText = text.replace(/^\)\]\}'/, '').trim();
|
|
18
|
+
try {
|
|
19
|
+
const parsedResponse = JSON.parse(cleanedText);
|
|
20
|
+
if (!Array.isArray(parsedResponse) || parsedResponse.length === 0) {
|
|
21
|
+
throw new ParseError('Invalid response format: empty array');
|
|
22
|
+
}
|
|
23
|
+
const nestedJsonString = parsedResponse[0][2];
|
|
24
|
+
if (!nestedJsonString) {
|
|
25
|
+
throw new ParseError('Invalid response format: missing nested JSON');
|
|
26
|
+
}
|
|
27
|
+
const data = JSON.parse(nestedJsonString);
|
|
28
|
+
if (!data || !Array.isArray(data) || data.length < 2) {
|
|
29
|
+
throw new ParseError('Invalid response format: missing data array');
|
|
30
|
+
}
|
|
31
|
+
return updateResponseObject(data[1]);
|
|
32
|
+
}
|
|
33
|
+
catch (e) {
|
|
34
|
+
if (e instanceof ParseError) {
|
|
35
|
+
throw e;
|
|
36
|
+
}
|
|
37
|
+
throw new ParseError('Failed to parse response');
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
const updateResponseObject = (data) => {
|
|
41
|
+
if (!Array.isArray(data)) {
|
|
42
|
+
throw new ParseError('Invalid data format: expected array');
|
|
43
|
+
}
|
|
44
|
+
const allTrendingStories = [];
|
|
45
|
+
const summary = [];
|
|
46
|
+
data.forEach((item) => {
|
|
47
|
+
if (Array.isArray(item)) {
|
|
48
|
+
const story = {
|
|
49
|
+
title: String(item[0] || ''),
|
|
50
|
+
traffic: String(item[6] || '0'),
|
|
51
|
+
articles: Array.isArray(item[9]) ? item[9].map((article) => ({
|
|
52
|
+
title: String(article[0] || ''),
|
|
53
|
+
url: String(article[1] || ''),
|
|
54
|
+
source: String(article[2] || ''),
|
|
55
|
+
time: String(article[3] || ''),
|
|
56
|
+
snippet: String(article[4] || '')
|
|
57
|
+
})) : [],
|
|
58
|
+
shareUrl: String(item[12] || '')
|
|
59
|
+
};
|
|
60
|
+
if (item[1]) {
|
|
61
|
+
story.image = {
|
|
62
|
+
newsUrl: String(item[1][0] || ''),
|
|
63
|
+
source: String(item[1][1] || ''),
|
|
64
|
+
imageUrl: String(item[1][2] || '')
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
allTrendingStories.push(story);
|
|
68
|
+
summary.push({
|
|
69
|
+
title: story.title,
|
|
70
|
+
traffic: story.traffic,
|
|
71
|
+
articles: story.articles
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
return { allTrendingStories, summary };
|
|
76
|
+
};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { DailyTrendingTopics, DailyTrendingTopicsOptions, RealTimeTrendsOptions, ExploreOptions, ExploreResponse, InterestByRegionOptions, InterestByRegionResponse, GoogleTrendsResponse, RelatedTopicsResponse, RelatedQueriesResponse, RelatedData } from '../types/index';
|
|
2
|
+
export declare class GoogleTrendsApi {
|
|
3
|
+
/**
|
|
4
|
+
* Get autocomplete suggestions for a keyword
|
|
5
|
+
* @param keyword - The keyword to get suggestions for
|
|
6
|
+
* @param hl - Language code (default: 'en-US')
|
|
7
|
+
* @returns Promise with array of suggestion strings
|
|
8
|
+
*/
|
|
9
|
+
autocomplete(keyword: string, hl?: string): Promise<GoogleTrendsResponse<string[]>>;
|
|
10
|
+
/**
|
|
11
|
+
* Get daily trending topics
|
|
12
|
+
* @param options - Options for daily trends request
|
|
13
|
+
* @returns Promise with trending topics data
|
|
14
|
+
*/
|
|
15
|
+
dailyTrends({ geo, lang }: DailyTrendingTopicsOptions): Promise<GoogleTrendsResponse<DailyTrendingTopics>>;
|
|
16
|
+
/**
|
|
17
|
+
* Get real-time trending topics
|
|
18
|
+
* @param options - Options for real-time trends request
|
|
19
|
+
* @returns Promise with trending topics data
|
|
20
|
+
*/
|
|
21
|
+
realTimeTrends({ geo, trendingHours }: RealTimeTrendsOptions): Promise<GoogleTrendsResponse<DailyTrendingTopics>>;
|
|
22
|
+
explore({ keyword, geo, time, category, property, hl, }: ExploreOptions): Promise<ExploreResponse>;
|
|
23
|
+
interestByRegion({ keyword, startTime, endTime, geo, resolution, hl, timezone, category }: InterestByRegionOptions): Promise<InterestByRegionResponse>;
|
|
24
|
+
relatedTopics({ keyword, geo, time, category, property, hl, }: ExploreOptions): Promise<GoogleTrendsResponse<RelatedTopicsResponse>>;
|
|
25
|
+
relatedQueries({ keyword, geo, time, category, property, hl, }: ExploreOptions): Promise<GoogleTrendsResponse<RelatedQueriesResponse>>;
|
|
26
|
+
relatedData({ keyword, geo, time, category, property, hl, }: ExploreOptions): Promise<GoogleTrendsResponse<RelatedData>>;
|
|
27
|
+
}
|
|
28
|
+
declare const _default: GoogleTrendsApi;
|
|
29
|
+
export default _default;
|
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
import { GoogleTrendsEndpoints } from '../types/enums';
|
|
2
|
+
import { request } from './request';
|
|
3
|
+
import { extractJsonFromResponse } from './format';
|
|
4
|
+
import { GOOGLE_TRENDS_MAPPER } from '../constants';
|
|
5
|
+
import { NetworkError, ParseError, UnknownError, } from '../errors/GoogleTrendsError';
|
|
6
|
+
export class GoogleTrendsApi {
|
|
7
|
+
/**
|
|
8
|
+
* Get autocomplete suggestions for a keyword
|
|
9
|
+
* @param keyword - The keyword to get suggestions for
|
|
10
|
+
* @param hl - Language code (default: 'en-US')
|
|
11
|
+
* @returns Promise with array of suggestion strings
|
|
12
|
+
*/
|
|
13
|
+
async autocomplete(keyword, hl = 'en-US') {
|
|
14
|
+
if (!keyword) {
|
|
15
|
+
return { data: [] };
|
|
16
|
+
}
|
|
17
|
+
const options = {
|
|
18
|
+
...GOOGLE_TRENDS_MAPPER[GoogleTrendsEndpoints.autocomplete],
|
|
19
|
+
qs: {
|
|
20
|
+
hl,
|
|
21
|
+
tz: '240',
|
|
22
|
+
},
|
|
23
|
+
};
|
|
24
|
+
try {
|
|
25
|
+
const response = await request(`${options.url}/${encodeURIComponent(keyword)}`, options);
|
|
26
|
+
const text = await response.text();
|
|
27
|
+
// Remove the first 5 characters (JSONP wrapper) and parse
|
|
28
|
+
const data = JSON.parse(text.slice(5));
|
|
29
|
+
return { data: data.default.topics.map((topic) => topic.title) };
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
if (error instanceof Error) {
|
|
33
|
+
return { error: new NetworkError(error.message) };
|
|
34
|
+
}
|
|
35
|
+
return { error: new UnknownError() };
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Get daily trending topics
|
|
40
|
+
* @param options - Options for daily trends request
|
|
41
|
+
* @returns Promise with trending topics data
|
|
42
|
+
*/
|
|
43
|
+
async dailyTrends({ geo = 'US', lang = 'en' }) {
|
|
44
|
+
const defaultOptions = GOOGLE_TRENDS_MAPPER[GoogleTrendsEndpoints.dailyTrends];
|
|
45
|
+
const options = {
|
|
46
|
+
...defaultOptions,
|
|
47
|
+
body: new URLSearchParams({
|
|
48
|
+
'f.req': `[[["i0OFE","[null,null,\\"${geo}\\",0,\\"${lang}\\",24,1]",null,"generic"]]]`,
|
|
49
|
+
}).toString(),
|
|
50
|
+
contentType: 'form'
|
|
51
|
+
};
|
|
52
|
+
try {
|
|
53
|
+
const response = await request(options.url, options);
|
|
54
|
+
const text = await response.text();
|
|
55
|
+
const trendingTopics = extractJsonFromResponse(text);
|
|
56
|
+
if (!trendingTopics) {
|
|
57
|
+
return { error: new ParseError() };
|
|
58
|
+
}
|
|
59
|
+
return { data: trendingTopics };
|
|
60
|
+
}
|
|
61
|
+
catch (error) {
|
|
62
|
+
if (error instanceof Error) {
|
|
63
|
+
return { error: new NetworkError(error.message) };
|
|
64
|
+
}
|
|
65
|
+
return { error: new UnknownError() };
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Get real-time trending topics
|
|
70
|
+
* @param options - Options for real-time trends request
|
|
71
|
+
* @returns Promise with trending topics data
|
|
72
|
+
*/
|
|
73
|
+
async realTimeTrends({ geo = 'US', trendingHours = 4 }) {
|
|
74
|
+
const defaultOptions = GOOGLE_TRENDS_MAPPER[GoogleTrendsEndpoints.dailyTrends];
|
|
75
|
+
const options = {
|
|
76
|
+
...defaultOptions,
|
|
77
|
+
body: new URLSearchParams({
|
|
78
|
+
'f.req': `[[["i0OFE","[null,null,\\"${geo}\\",0,\\"en\\",${trendingHours},1]",null,"generic"]]]`,
|
|
79
|
+
}).toString(),
|
|
80
|
+
contentType: 'form'
|
|
81
|
+
};
|
|
82
|
+
try {
|
|
83
|
+
const response = await request(options.url, options);
|
|
84
|
+
const text = await response.text();
|
|
85
|
+
const trendingTopics = extractJsonFromResponse(text);
|
|
86
|
+
if (!trendingTopics) {
|
|
87
|
+
return { error: new ParseError() };
|
|
88
|
+
}
|
|
89
|
+
return { data: trendingTopics };
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
if (error instanceof Error) {
|
|
93
|
+
return { error: new NetworkError(error.message) };
|
|
94
|
+
}
|
|
95
|
+
return { error: new UnknownError() };
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
async explore({ keyword, geo = 'US', time = 'now 1-d', category = 0, property = '', hl = 'en-US', }) {
|
|
99
|
+
const options = {
|
|
100
|
+
...GOOGLE_TRENDS_MAPPER[GoogleTrendsEndpoints.explore],
|
|
101
|
+
qs: {
|
|
102
|
+
hl,
|
|
103
|
+
tz: '240',
|
|
104
|
+
req: JSON.stringify({
|
|
105
|
+
comparisonItem: [
|
|
106
|
+
{
|
|
107
|
+
keyword,
|
|
108
|
+
geo,
|
|
109
|
+
time,
|
|
110
|
+
},
|
|
111
|
+
],
|
|
112
|
+
category,
|
|
113
|
+
property,
|
|
114
|
+
}),
|
|
115
|
+
},
|
|
116
|
+
contentType: 'form'
|
|
117
|
+
};
|
|
118
|
+
try {
|
|
119
|
+
const response = await request(options.url, options);
|
|
120
|
+
const text = await response.text();
|
|
121
|
+
// Check if response is HTML (error page)
|
|
122
|
+
if (text.includes('<html') || text.includes('<!DOCTYPE')) {
|
|
123
|
+
console.error('Explore request returned HTML instead of JSON');
|
|
124
|
+
return { widgets: [] };
|
|
125
|
+
}
|
|
126
|
+
// Try to parse as JSON
|
|
127
|
+
try {
|
|
128
|
+
// Remove the first 5 characters (JSONP wrapper) and parse
|
|
129
|
+
const data = JSON.parse(text.slice(5));
|
|
130
|
+
return data;
|
|
131
|
+
}
|
|
132
|
+
catch (parseError) {
|
|
133
|
+
console.error('Failed to parse explore response as JSON:', parseError instanceof Error ? parseError.message : 'Unknown parse error');
|
|
134
|
+
console.error('Response preview:', text.substring(0, 200));
|
|
135
|
+
return { widgets: [] };
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
catch (error) {
|
|
139
|
+
console.error('Explore request failed:', error);
|
|
140
|
+
return { widgets: [] };
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
//
|
|
144
|
+
async interestByRegion({ keyword, startTime = new Date('2004-01-01'), endTime = new Date(), geo = 'US', resolution = 'REGION', hl = 'en-US', timezone = new Date().getTimezoneOffset(), category = 0 }) {
|
|
145
|
+
const formatDate = (date) => {
|
|
146
|
+
return date.toISOString().split('T')[0];
|
|
147
|
+
};
|
|
148
|
+
const formatTrendsDate = (date) => {
|
|
149
|
+
const pad = (n) => n.toString().padStart(2, '0');
|
|
150
|
+
const yyyy = date.getFullYear();
|
|
151
|
+
const mm = pad(date.getMonth() + 1);
|
|
152
|
+
const dd = pad(date.getDate());
|
|
153
|
+
const hh = pad(date.getHours());
|
|
154
|
+
const min = pad(date.getMinutes());
|
|
155
|
+
const ss = pad(date.getSeconds());
|
|
156
|
+
return `${yyyy}-${mm}-${dd}T${hh}\\:${min}\\:${ss}`;
|
|
157
|
+
};
|
|
158
|
+
const getDateRangeParam = (date) => {
|
|
159
|
+
const yesterday = new Date(date);
|
|
160
|
+
yesterday.setDate(date.getDate() - 1);
|
|
161
|
+
const formattedStart = formatTrendsDate(yesterday);
|
|
162
|
+
const formattedEnd = formatTrendsDate(date);
|
|
163
|
+
return `${formattedStart} ${formattedEnd}`;
|
|
164
|
+
};
|
|
165
|
+
const exploreResponse = await this.explore({
|
|
166
|
+
keyword: Array.isArray(keyword) ? keyword[0] : keyword,
|
|
167
|
+
geo: Array.isArray(geo) ? geo[0] : geo,
|
|
168
|
+
time: `${getDateRangeParam(startTime)} ${getDateRangeParam(endTime)}`,
|
|
169
|
+
category,
|
|
170
|
+
hl
|
|
171
|
+
});
|
|
172
|
+
const widget = exploreResponse.widgets.find(w => w.id === 'GEO_MAP');
|
|
173
|
+
if (!widget) {
|
|
174
|
+
return { default: { geoMapData: [] } };
|
|
175
|
+
}
|
|
176
|
+
const options = {
|
|
177
|
+
...GOOGLE_TRENDS_MAPPER[GoogleTrendsEndpoints.interestByRegion],
|
|
178
|
+
qs: {
|
|
179
|
+
hl,
|
|
180
|
+
tz: timezone.toString(),
|
|
181
|
+
req: JSON.stringify({
|
|
182
|
+
geo: {
|
|
183
|
+
country: Array.isArray(geo) ? geo[0] : geo
|
|
184
|
+
},
|
|
185
|
+
comparisonItem: [{
|
|
186
|
+
time: `${formatDate(startTime)} ${formatDate(endTime)}`,
|
|
187
|
+
complexKeywordsRestriction: {
|
|
188
|
+
keyword: [{
|
|
189
|
+
type: 'BROAD', //'ENTITY',
|
|
190
|
+
value: Array.isArray(keyword) ? keyword[0] : keyword
|
|
191
|
+
}]
|
|
192
|
+
}
|
|
193
|
+
}],
|
|
194
|
+
resolution,
|
|
195
|
+
locale: hl,
|
|
196
|
+
requestOptions: {
|
|
197
|
+
property: '',
|
|
198
|
+
backend: 'CM', //'IZG',
|
|
199
|
+
category
|
|
200
|
+
},
|
|
201
|
+
userConfig: {
|
|
202
|
+
userType: 'USER_TYPE_LEGIT_USER'
|
|
203
|
+
}
|
|
204
|
+
}),
|
|
205
|
+
token: widget.token
|
|
206
|
+
}
|
|
207
|
+
};
|
|
208
|
+
try {
|
|
209
|
+
const response = await request(options.url, options);
|
|
210
|
+
const text = await response.text();
|
|
211
|
+
// Remove the first 5 characters (JSONP wrapper) and parse
|
|
212
|
+
const data = JSON.parse(text.slice(5));
|
|
213
|
+
return data;
|
|
214
|
+
}
|
|
215
|
+
catch (error) {
|
|
216
|
+
return { default: { geoMapData: [] } };
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
async relatedTopics({ keyword, geo = 'US', time = 'now 1-d', category = 0, property = '', hl = 'en-US', }) {
|
|
220
|
+
try {
|
|
221
|
+
// Validate keyword
|
|
222
|
+
if (!keyword || keyword.trim() === '') {
|
|
223
|
+
return { error: new ParseError() };
|
|
224
|
+
}
|
|
225
|
+
const autocompleteResult = await this.autocomplete(keyword, hl);
|
|
226
|
+
if (autocompleteResult.error) {
|
|
227
|
+
return { error: autocompleteResult.error };
|
|
228
|
+
}
|
|
229
|
+
const relatedTopics = autocompleteResult.data?.slice(0, 10).map((suggestion, index) => ({
|
|
230
|
+
topic: {
|
|
231
|
+
mid: `/m/${index}`,
|
|
232
|
+
title: suggestion,
|
|
233
|
+
type: 'Topic'
|
|
234
|
+
},
|
|
235
|
+
value: 100 - index * 10,
|
|
236
|
+
formattedValue: (100 - index * 10).toString(),
|
|
237
|
+
hasData: true,
|
|
238
|
+
link: `/trends/explore?q=${encodeURIComponent(suggestion)}&date=${time}&geo=${geo}`
|
|
239
|
+
})) || [];
|
|
240
|
+
return {
|
|
241
|
+
data: {
|
|
242
|
+
default: {
|
|
243
|
+
rankedList: [{
|
|
244
|
+
rankedKeyword: relatedTopics
|
|
245
|
+
}]
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
catch (error) {
|
|
251
|
+
if (error instanceof Error) {
|
|
252
|
+
return { error: new NetworkError(error.message) };
|
|
253
|
+
}
|
|
254
|
+
return { error: new UnknownError() };
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
async relatedQueries({ keyword, geo = 'US', time = 'now 1-d', category = 0, property = '', hl = 'en-US', }) {
|
|
258
|
+
try {
|
|
259
|
+
// Validate keyword
|
|
260
|
+
if (!keyword || keyword.trim() === '') {
|
|
261
|
+
return { error: new ParseError() };
|
|
262
|
+
}
|
|
263
|
+
const autocompleteResult = await this.autocomplete(keyword, hl);
|
|
264
|
+
if (autocompleteResult.error) {
|
|
265
|
+
return { error: autocompleteResult.error };
|
|
266
|
+
}
|
|
267
|
+
const relatedQueries = autocompleteResult.data?.slice(0, 10).map((suggestion, index) => ({
|
|
268
|
+
query: suggestion,
|
|
269
|
+
value: 100 - index * 10,
|
|
270
|
+
formattedValue: (100 - index * 10).toString(),
|
|
271
|
+
hasData: true,
|
|
272
|
+
link: `/trends/explore?q=${encodeURIComponent(suggestion)}&date=${time}&geo=${geo}`
|
|
273
|
+
})) || [];
|
|
274
|
+
return {
|
|
275
|
+
data: {
|
|
276
|
+
default: {
|
|
277
|
+
rankedList: [{
|
|
278
|
+
rankedKeyword: relatedQueries
|
|
279
|
+
}]
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
catch (error) {
|
|
285
|
+
if (error instanceof Error) {
|
|
286
|
+
return { error: new NetworkError(error.message) };
|
|
287
|
+
}
|
|
288
|
+
return { error: new UnknownError() };
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
async relatedData({ keyword, geo = 'US', time = 'now 1-d', category = 0, property = '', hl = 'en-US', }) {
|
|
292
|
+
try {
|
|
293
|
+
// Validate keyword
|
|
294
|
+
if (!keyword || keyword.trim() === '') {
|
|
295
|
+
return { error: new ParseError() };
|
|
296
|
+
}
|
|
297
|
+
const autocompleteResult = await this.autocomplete(keyword, hl);
|
|
298
|
+
if (autocompleteResult.error) {
|
|
299
|
+
return { error: autocompleteResult.error };
|
|
300
|
+
}
|
|
301
|
+
const suggestions = autocompleteResult.data?.slice(0, 10) || [];
|
|
302
|
+
const topics = suggestions.map((suggestion, index) => ({
|
|
303
|
+
topic: {
|
|
304
|
+
mid: `/m/${index}`,
|
|
305
|
+
title: suggestion,
|
|
306
|
+
type: 'Topic'
|
|
307
|
+
},
|
|
308
|
+
value: 100 - index * 10,
|
|
309
|
+
formattedValue: (100 - index * 10).toString(),
|
|
310
|
+
hasData: true,
|
|
311
|
+
link: `/trends/explore?q=${encodeURIComponent(suggestion)}&date=${time}&geo=${geo}`
|
|
312
|
+
}));
|
|
313
|
+
const queries = suggestions.map((suggestion, index) => ({
|
|
314
|
+
query: suggestion,
|
|
315
|
+
value: 100 - index * 10,
|
|
316
|
+
formattedValue: (100 - index * 10).toString(),
|
|
317
|
+
hasData: true,
|
|
318
|
+
link: `/trends/explore?q=${encodeURIComponent(suggestion)}&date=${time}&geo=${geo}`
|
|
319
|
+
}));
|
|
320
|
+
return {
|
|
321
|
+
data: {
|
|
322
|
+
topics,
|
|
323
|
+
queries
|
|
324
|
+
}
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
catch (error) {
|
|
328
|
+
if (error instanceof Error) {
|
|
329
|
+
return { error: new NetworkError(error.message) };
|
|
330
|
+
}
|
|
331
|
+
return { error: new UnknownError() };
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
export default new GoogleTrendsApi();
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export declare const request: (url: string, options: {
|
|
2
|
+
method?: string;
|
|
3
|
+
qs?: Record<string, any>;
|
|
4
|
+
body?: string | Record<string, any>;
|
|
5
|
+
headers?: Record<string, string>;
|
|
6
|
+
contentType?: "json" | "form";
|
|
7
|
+
}) => Promise<{
|
|
8
|
+
text: () => Promise<string>;
|
|
9
|
+
}>;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import https from 'https';
|
|
2
|
+
import querystring from 'querystring';
|
|
3
|
+
let cookieVal;
|
|
4
|
+
function rereq(options, body) {
|
|
5
|
+
return new Promise((resolve, reject) => {
|
|
6
|
+
const req = https.request(options, (res) => {
|
|
7
|
+
let chunk = '';
|
|
8
|
+
res.on('data', (data) => { chunk += data; });
|
|
9
|
+
res.on('end', () => resolve(chunk));
|
|
10
|
+
});
|
|
11
|
+
req.on('error', reject);
|
|
12
|
+
if (body)
|
|
13
|
+
req.write(body);
|
|
14
|
+
req.end();
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
export const request = async (url, options) => {
|
|
18
|
+
const parsedUrl = new URL(url);
|
|
19
|
+
const method = options.method || 'POST';
|
|
20
|
+
// Prepare body
|
|
21
|
+
let bodyString = '';
|
|
22
|
+
const contentType = options.contentType || 'json';
|
|
23
|
+
if (typeof options.body === 'string') {
|
|
24
|
+
bodyString = options.body;
|
|
25
|
+
}
|
|
26
|
+
else if (contentType === 'form') {
|
|
27
|
+
bodyString = querystring.stringify(options.body || {});
|
|
28
|
+
}
|
|
29
|
+
else if (options.body) {
|
|
30
|
+
bodyString = JSON.stringify(options.body);
|
|
31
|
+
}
|
|
32
|
+
const requestOptions = {
|
|
33
|
+
hostname: parsedUrl.hostname,
|
|
34
|
+
port: parsedUrl.port || 443,
|
|
35
|
+
path: `${parsedUrl.pathname}${options.qs ? '?' + querystring.stringify(options.qs) : ''}`,
|
|
36
|
+
method,
|
|
37
|
+
headers: {
|
|
38
|
+
...(options.headers || {}),
|
|
39
|
+
...(contentType === 'form'
|
|
40
|
+
? { 'Content-Type': 'application/x-www-form-urlencoded' }
|
|
41
|
+
: { 'Content-Type': 'application/json' }),
|
|
42
|
+
...(bodyString ? { 'Content-Length': Buffer.byteLength(bodyString).toString() } : {}),
|
|
43
|
+
...(cookieVal ? { cookie: cookieVal } : {})
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
const response = await new Promise((resolve, reject) => {
|
|
47
|
+
const req = https.request(requestOptions, (res) => {
|
|
48
|
+
let chunk = '';
|
|
49
|
+
res.on('data', (data) => { chunk += data; });
|
|
50
|
+
res.on('end', async () => {
|
|
51
|
+
if (res.statusCode === 429 && res.headers['set-cookie']) {
|
|
52
|
+
cookieVal = res.headers['set-cookie'][0].split(';')[0];
|
|
53
|
+
requestOptions.headers['cookie'] = cookieVal;
|
|
54
|
+
try {
|
|
55
|
+
const retryResponse = await rereq(requestOptions, bodyString);
|
|
56
|
+
resolve(retryResponse);
|
|
57
|
+
}
|
|
58
|
+
catch (err) {
|
|
59
|
+
reject(err);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
else {
|
|
63
|
+
resolve(chunk);
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
});
|
|
67
|
+
req.on('error', reject);
|
|
68
|
+
if (bodyString)
|
|
69
|
+
req.write(bodyString);
|
|
70
|
+
req.end();
|
|
71
|
+
});
|
|
72
|
+
return {
|
|
73
|
+
text: () => Promise.resolve(response)
|
|
74
|
+
};
|
|
75
|
+
};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export declare const dailyTrends: ({ geo, lang }: import("./types").DailyTrendingTopicsOptions) => Promise<import("./types").GoogleTrendsResponse<import("./types").DailyTrendingTopics>>;
|
|
2
|
+
export declare const realTimeTrends: ({ geo, trendingHours }: import("./types").RealTimeTrendsOptions) => Promise<import("./types").GoogleTrendsResponse<import("./types").DailyTrendingTopics>>;
|
|
3
|
+
export declare const autocomplete: (keyword: string, hl?: string) => Promise<import("./types").GoogleTrendsResponse<string[]>>;
|
|
4
|
+
export declare const explore: ({ keyword, geo, time, category, property, hl, }: import("./types").ExploreOptions) => Promise<import("./types").ExploreResponse>;
|
|
5
|
+
export declare const interestByRegion: ({ keyword, startTime, endTime, geo, resolution, hl, timezone, category }: import("./types").InterestByRegionOptions) => Promise<import("./types").InterestByRegionResponse>;
|
|
6
|
+
export declare const relatedTopics: ({ keyword, geo, time, category, property, hl, }: import("./types").ExploreOptions) => Promise<import("./types").GoogleTrendsResponse<import("./types").RelatedTopicsResponse>>;
|
|
7
|
+
export declare const relatedQueries: ({ keyword, geo, time, category, property, hl, }: import("./types").ExploreOptions) => Promise<import("./types").GoogleTrendsResponse<import("./types").RelatedQueriesResponse>>;
|
|
8
|
+
export declare const relatedData: ({ keyword, geo, time, category, property, hl, }: import("./types").ExploreOptions) => Promise<import("./types").GoogleTrendsResponse<import("./types").RelatedData>>;
|
|
9
|
+
declare const _default: {
|
|
10
|
+
dailyTrends: ({ geo, lang }: import("./types").DailyTrendingTopicsOptions) => Promise<import("./types").GoogleTrendsResponse<import("./types").DailyTrendingTopics>>;
|
|
11
|
+
realTimeTrends: ({ geo, trendingHours }: import("./types").RealTimeTrendsOptions) => Promise<import("./types").GoogleTrendsResponse<import("./types").DailyTrendingTopics>>;
|
|
12
|
+
autocomplete: (keyword: string, hl?: string) => Promise<import("./types").GoogleTrendsResponse<string[]>>;
|
|
13
|
+
explore: ({ keyword, geo, time, category, property, hl, }: import("./types").ExploreOptions) => Promise<import("./types").ExploreResponse>;
|
|
14
|
+
interestByRegion: ({ keyword, startTime, endTime, geo, resolution, hl, timezone, category }: import("./types").InterestByRegionOptions) => Promise<import("./types").InterestByRegionResponse>;
|
|
15
|
+
relatedTopics: ({ keyword, geo, time, category, property, hl, }: import("./types").ExploreOptions) => Promise<import("./types").GoogleTrendsResponse<import("./types").RelatedTopicsResponse>>;
|
|
16
|
+
relatedQueries: ({ keyword, geo, time, category, property, hl, }: import("./types").ExploreOptions) => Promise<import("./types").GoogleTrendsResponse<import("./types").RelatedQueriesResponse>>;
|
|
17
|
+
relatedData: ({ keyword, geo, time, category, property, hl, }: import("./types").ExploreOptions) => Promise<import("./types").GoogleTrendsResponse<import("./types").RelatedData>>;
|
|
18
|
+
};
|
|
19
|
+
export default _default;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { GoogleTrendsApi } from './helpers/googleTrendsAPI';
|
|
2
|
+
const api = new GoogleTrendsApi();
|
|
3
|
+
export const dailyTrends = api.dailyTrends.bind(api);
|
|
4
|
+
export const realTimeTrends = api.realTimeTrends.bind(api);
|
|
5
|
+
export const autocomplete = api.autocomplete.bind(api);
|
|
6
|
+
export const explore = api.explore.bind(api);
|
|
7
|
+
export const interestByRegion = api.interestByRegion.bind(api);
|
|
8
|
+
export const relatedTopics = api.relatedTopics.bind(api);
|
|
9
|
+
export const relatedQueries = api.relatedQueries.bind(api);
|
|
10
|
+
export const relatedData = api.relatedData.bind(api);
|
|
11
|
+
// Default export for CommonJS compatibility
|
|
12
|
+
export default {
|
|
13
|
+
dailyTrends,
|
|
14
|
+
realTimeTrends,
|
|
15
|
+
autocomplete,
|
|
16
|
+
explore,
|
|
17
|
+
interestByRegion,
|
|
18
|
+
relatedTopics,
|
|
19
|
+
relatedQueries,
|
|
20
|
+
relatedData
|
|
21
|
+
};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export declare enum GoogleTrendsEndpoints {
|
|
2
|
+
dailyTrends = "dailyTrends",
|
|
3
|
+
autocomplete = "autocomplete",
|
|
4
|
+
explore = "explore",
|
|
5
|
+
interestByRegion = "interestByRegion",
|
|
6
|
+
relatedTopics = "relatedTopics",
|
|
7
|
+
relatedQueries = "relatedQueries"
|
|
8
|
+
}
|
|
9
|
+
export declare enum GoogleTrendsTrendingHours {
|
|
10
|
+
fourHrs = 4,
|
|
11
|
+
oneDay = 24,
|
|
12
|
+
twoDays = 48,
|
|
13
|
+
sevenDays = 168
|
|
14
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export var GoogleTrendsEndpoints;
|
|
2
|
+
(function (GoogleTrendsEndpoints) {
|
|
3
|
+
GoogleTrendsEndpoints["dailyTrends"] = "dailyTrends";
|
|
4
|
+
GoogleTrendsEndpoints["autocomplete"] = "autocomplete";
|
|
5
|
+
GoogleTrendsEndpoints["explore"] = "explore";
|
|
6
|
+
GoogleTrendsEndpoints["interestByRegion"] = "interestByRegion";
|
|
7
|
+
GoogleTrendsEndpoints["relatedTopics"] = "relatedTopics";
|
|
8
|
+
GoogleTrendsEndpoints["relatedQueries"] = "relatedQueries";
|
|
9
|
+
})(GoogleTrendsEndpoints || (GoogleTrendsEndpoints = {}));
|
|
10
|
+
export var GoogleTrendsTrendingHours;
|
|
11
|
+
(function (GoogleTrendsTrendingHours) {
|
|
12
|
+
GoogleTrendsTrendingHours[GoogleTrendsTrendingHours["fourHrs"] = 4] = "fourHrs";
|
|
13
|
+
GoogleTrendsTrendingHours[GoogleTrendsTrendingHours["oneDay"] = 24] = "oneDay";
|
|
14
|
+
GoogleTrendsTrendingHours[GoogleTrendsTrendingHours["twoDays"] = 48] = "twoDays";
|
|
15
|
+
GoogleTrendsTrendingHours[GoogleTrendsTrendingHours["sevenDays"] = 168] = "sevenDays";
|
|
16
|
+
})(GoogleTrendsTrendingHours || (GoogleTrendsTrendingHours = {}));
|