@shaivpidadi/trends-js 0.0.0-beta.5 → 0.0.0-beta.6

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.
@@ -0,0 +1,23 @@
1
+ import { GoogleTrendsError } from '../types';
2
+ export declare class RateLimitError extends Error implements GoogleTrendsError {
3
+ code: string;
4
+ statusCode: number;
5
+ constructor(message?: string);
6
+ }
7
+ export declare class InvalidRequestError extends Error implements GoogleTrendsError {
8
+ code: string;
9
+ statusCode: number;
10
+ constructor(message?: string);
11
+ }
12
+ export declare class NetworkError extends Error implements GoogleTrendsError {
13
+ code: string;
14
+ constructor(message?: string);
15
+ }
16
+ export declare class ParseError extends Error implements GoogleTrendsError {
17
+ code: string;
18
+ constructor(message?: string);
19
+ }
20
+ export declare class UnknownError extends Error implements GoogleTrendsError {
21
+ code: string;
22
+ constructor(message?: string);
23
+ }
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.UnknownError = exports.ParseError = exports.NetworkError = exports.InvalidRequestError = exports.RateLimitError = void 0;
4
+ class RateLimitError extends Error {
5
+ constructor(message = 'Rate limit exceeded') {
6
+ super(message);
7
+ this.code = 'RATE_LIMIT_EXCEEDED';
8
+ this.statusCode = 429;
9
+ this.name = 'RateLimitError';
10
+ }
11
+ }
12
+ exports.RateLimitError = RateLimitError;
13
+ class InvalidRequestError extends Error {
14
+ constructor(message = 'Invalid request parameters') {
15
+ super(message);
16
+ this.code = 'INVALID_REQUEST';
17
+ this.statusCode = 400;
18
+ this.name = 'InvalidRequestError';
19
+ }
20
+ }
21
+ exports.InvalidRequestError = InvalidRequestError;
22
+ class NetworkError extends Error {
23
+ constructor(message = 'Network request failed') {
24
+ super(message);
25
+ this.code = 'NETWORK_ERROR';
26
+ this.name = 'NetworkError';
27
+ }
28
+ }
29
+ exports.NetworkError = NetworkError;
30
+ class ParseError extends Error {
31
+ constructor(message = 'Failed to parse response') {
32
+ super(message);
33
+ this.code = 'PARSE_ERROR';
34
+ this.name = 'ParseError';
35
+ }
36
+ }
37
+ exports.ParseError = ParseError;
38
+ class UnknownError extends Error {
39
+ constructor(message = 'An unknown error occurred') {
40
+ super(message);
41
+ this.code = 'UNKNOWN_ERROR';
42
+ this.name = 'UnknownError';
43
+ }
44
+ }
45
+ exports.UnknownError = UnknownError;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.extractJsonFromResponse = void 0;
4
+ const GoogleTrendsError_1 = require("../errors/GoogleTrendsError");
4
5
  // For future refrence and update: from google trends page rpc call response,
5
6
  // 0 "twitter down" The main trending search term.
6
7
  // 1 null Unused (reserved for future Google Trends data).
@@ -20,33 +21,59 @@ const extractJsonFromResponse = (text) => {
20
21
  try {
21
22
  const parsedResponse = JSON.parse(cleanedText);
22
23
  if (!Array.isArray(parsedResponse) || parsedResponse.length === 0) {
23
- return null;
24
+ throw new GoogleTrendsError_1.ParseError('Invalid response format: empty array');
24
25
  }
25
26
  const nestedJsonString = parsedResponse[0][2];
26
27
  if (!nestedJsonString) {
27
- return null;
28
+ throw new GoogleTrendsError_1.ParseError('Invalid response format: missing nested JSON');
28
29
  }
29
30
  const data = JSON.parse(nestedJsonString);
30
31
  if (!data || !Array.isArray(data) || data.length < 2) {
31
- return null;
32
+ throw new GoogleTrendsError_1.ParseError('Invalid response format: missing data array');
32
33
  }
33
34
  return updateResponseObject(data[1]);
34
35
  }
35
36
  catch (e) {
36
- console.error('Failed to parse response:', e);
37
- return null;
37
+ if (e instanceof GoogleTrendsError_1.ParseError) {
38
+ throw e;
39
+ }
40
+ throw new GoogleTrendsError_1.ParseError('Failed to parse response');
38
41
  }
39
42
  };
40
43
  exports.extractJsonFromResponse = extractJsonFromResponse;
41
44
  const updateResponseObject = (data) => {
42
45
  if (!Array.isArray(data)) {
43
- return null;
46
+ throw new GoogleTrendsError_1.ParseError('Invalid data format: expected array');
44
47
  }
45
- const allTrendingStories = data;
48
+ const allTrendingStories = [];
46
49
  const summary = [];
47
50
  data.forEach((item) => {
48
- if (Array.isArray(item) && typeof item[0] === 'string') {
49
- summary.push(item[0]); // First element is usually the trending keyword
51
+ if (Array.isArray(item)) {
52
+ const story = {
53
+ title: String(item[0] || ''),
54
+ traffic: String(item[6] || '0'),
55
+ articles: Array.isArray(item[9]) ? item[9].map((article) => ({
56
+ title: String(article[0] || ''),
57
+ url: String(article[1] || ''),
58
+ source: String(article[2] || ''),
59
+ time: String(article[3] || ''),
60
+ snippet: String(article[4] || '')
61
+ })) : [],
62
+ shareUrl: String(item[12] || '')
63
+ };
64
+ if (item[1]) {
65
+ story.image = {
66
+ newsUrl: String(item[1][0] || ''),
67
+ source: String(item[1][1] || ''),
68
+ imageUrl: String(item[1][2] || '')
69
+ };
70
+ }
71
+ allTrendingStories.push(story);
72
+ summary.push({
73
+ title: story.title,
74
+ traffic: story.traffic,
75
+ articles: story.articles
76
+ });
50
77
  }
51
78
  });
52
79
  return { allTrendingStories, summary };
@@ -1,8 +1,24 @@
1
- import { DailyTrendingTopics, DailyTrendingTopicsOptions, RealTimeTrendsOptions, ExploreOptions, ExploreResponse, InterestByRegionOptions, InterestByRegionResponse } from '../types/index';
1
+ import { DailyTrendingTopics, DailyTrendingTopicsOptions, RealTimeTrendsOptions, ExploreOptions, ExploreResponse, InterestByRegionOptions, InterestByRegionResponse, GoogleTrendsResponse } from '../types/index';
2
2
  export declare class GoogleTrendsApi {
3
- autocomplete(keyword: string, hl?: string): Promise<string[]>;
4
- dailyTrends({ geo, lang }: DailyTrendingTopicsOptions): Promise<DailyTrendingTopics>;
5
- realTimeTrends({ geo, trendingHours }: RealTimeTrendsOptions): Promise<DailyTrendingTopics>;
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>>;
6
22
  explore({ keyword, geo, time, category, property, hl, }: ExploreOptions): Promise<ExploreResponse>;
7
23
  interestByRegion({ keyword, startTime, endTime, geo, resolution, hl, timezone, category }: InterestByRegionOptions): Promise<InterestByRegionResponse>;
8
24
  }
@@ -13,11 +13,18 @@ exports.GoogleTrendsApi = void 0;
13
13
  const request_1 = require("./request");
14
14
  const format_1 = require("./format");
15
15
  const constants_1 = require("../constants");
16
+ const GoogleTrendsError_1 = require("../errors/GoogleTrendsError");
16
17
  class GoogleTrendsApi {
18
+ /**
19
+ * Get autocomplete suggestions for a keyword
20
+ * @param keyword - The keyword to get suggestions for
21
+ * @param hl - Language code (default: 'en-US')
22
+ * @returns Promise with array of suggestion strings
23
+ */
17
24
  autocomplete(keyword, hl = 'en-US') {
18
25
  return __awaiter(this, void 0, void 0, function* () {
19
26
  if (!keyword) {
20
- return [];
27
+ return { data: [] };
21
28
  }
22
29
  const options = Object.assign(Object.assign({}, constants_1.GOOGLE_TRENDS_MAPPER["autocomplete" /* GoogleTrendsEndpoints.autocomplete */]), { qs: {
23
30
  hl,
@@ -28,14 +35,21 @@ class GoogleTrendsApi {
28
35
  const text = yield response.text();
29
36
  // Remove the first 5 characters (JSONP wrapper) and parse
30
37
  const data = JSON.parse(text.slice(5));
31
- return data.default.topics.map((topic) => topic.title);
38
+ return { data: data.default.topics.map((topic) => topic.title) };
32
39
  }
33
40
  catch (error) {
34
- console.error('Autocomplete request failed:', error);
35
- return [];
41
+ if (error instanceof Error) {
42
+ return { error: new GoogleTrendsError_1.NetworkError(error.message) };
43
+ }
44
+ return { error: new GoogleTrendsError_1.UnknownError() };
36
45
  }
37
46
  });
38
47
  }
48
+ /**
49
+ * Get daily trending topics
50
+ * @param options - Options for daily trends request
51
+ * @returns Promise with trending topics data
52
+ */
39
53
  dailyTrends({ geo = 'US', lang = 'en' }) {
40
54
  return __awaiter(this, void 0, void 0, function* () {
41
55
  const defaultOptions = constants_1.GOOGLE_TRENDS_MAPPER["dailyTrends" /* GoogleTrendsEndpoints.dailyTrends */];
@@ -47,22 +61,23 @@ class GoogleTrendsApi {
47
61
  const text = yield response.text();
48
62
  const trendingTopics = (0, format_1.extractJsonFromResponse)(text);
49
63
  if (!trendingTopics) {
50
- return {
51
- allTrendingStories: [],
52
- summary: [],
53
- };
64
+ return { error: new GoogleTrendsError_1.ParseError() };
54
65
  }
55
- return trendingTopics;
66
+ return { data: trendingTopics };
56
67
  }
57
68
  catch (error) {
58
- console.error(error);
59
- return {
60
- allTrendingStories: [],
61
- summary: [],
62
- };
69
+ if (error instanceof Error) {
70
+ return { error: new GoogleTrendsError_1.NetworkError(error.message) };
71
+ }
72
+ return { error: new GoogleTrendsError_1.UnknownError() };
63
73
  }
64
74
  });
65
75
  }
76
+ /**
77
+ * Get real-time trending topics
78
+ * @param options - Options for real-time trends request
79
+ * @returns Promise with trending topics data
80
+ */
66
81
  realTimeTrends({ geo = 'US', trendingHours = 4 }) {
67
82
  return __awaiter(this, void 0, void 0, function* () {
68
83
  const defaultOptions = constants_1.GOOGLE_TRENDS_MAPPER["dailyTrends" /* GoogleTrendsEndpoints.dailyTrends */];
@@ -74,23 +89,19 @@ class GoogleTrendsApi {
74
89
  const text = yield response.text();
75
90
  const trendingTopics = (0, format_1.extractJsonFromResponse)(text);
76
91
  if (!trendingTopics) {
77
- return {
78
- allTrendingStories: [],
79
- summary: [],
80
- };
92
+ return { error: new GoogleTrendsError_1.ParseError() };
81
93
  }
82
- return trendingTopics;
94
+ return { data: trendingTopics };
83
95
  }
84
96
  catch (error) {
85
- console.error(error);
86
- return {
87
- allTrendingStories: [],
88
- summary: [],
89
- };
97
+ if (error instanceof Error) {
98
+ return { error: new GoogleTrendsError_1.NetworkError(error.message) };
99
+ }
100
+ return { error: new GoogleTrendsError_1.UnknownError() };
90
101
  }
91
102
  });
92
103
  }
93
- explore({ keyword, geo = 'US', time = 'today 12-m', category = 0, property = '', hl = 'en-US', }) {
104
+ explore({ keyword, geo = 'US', time = 'now 1-d', category = 0, property = '', hl = 'en-US', }) {
94
105
  return __awaiter(this, void 0, void 0, function* () {
95
106
  const options = Object.assign(Object.assign({}, constants_1.GOOGLE_TRENDS_MAPPER["explore" /* GoogleTrendsEndpoints.explore */]), { qs: {
96
107
  hl,
@@ -106,7 +117,7 @@ class GoogleTrendsApi {
106
117
  category,
107
118
  property,
108
119
  }),
109
- } });
120
+ }, contentType: 'form' });
110
121
  try {
111
122
  const response = yield (0, request_1.request)(options.url, options);
112
123
  const text = yield response.text();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shaivpidadi/trends-js",
3
- "version": "0.0.0-beta.5",
3
+ "version": "0.0.0-beta.6",
4
4
  "description": "Google Trends API for Node.js",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",