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
87
88
89
90
91
import {
NodeDescriberResult,
service,
} from "https://esm.town/v/dglazkov/servicefactory";
import {
parseXml,
XmlCdata,
XmlComment,
XmlDocument,
XmlElement,
XmlText,
} from "npm:@rgrove/parse-xml";
const firstChild = (element: XmlElement | XmlDocument) => {
return element.children.find((child) => "children" in child) as
| XmlElement
| undefined;
};
const elementsByName = (element: XmlElement, name: string): XmlElement[] => {
return element.children.filter((child) =>
("name" in child) && child.name === name
) as XmlElement[];
};
const elementsToJson = (element: XmlElement) => {
const json: Record<string, string> = {};
for (const child of element.children) {
if ("name" in child) {
const text = ("text" in child) ? child.text : null;
if (text) {
json[child.name] = text;
}
}
}
return json;
};
const parseTrends = (xml: XmlDocument) => {
const channel = firstChild(firstChild(xml));
console.log("channel", channel);
const items = elementsByName(channel, "item").map(elementsToJson);
return { items };
};
const getTrends = async ({ location }: { location: string }) => {
const url = `https://trends.google.com/trending/rss?geo=${location}`;
console.log("url", url);
const response = await fetch(url);
if (response.status !== 200) {
const error = await response.text();
return { $error: error };
}
const trendsData = await response.text();
const xml = parseXml(trendsData);
const result = parseTrends(xml);
return { result };
};
const describe = () => ({
title: "Google Trends - Trending Now",
description:
"Given a geographic location, returns the top trending topics in Google Trends.",
inputSchema: {
type: "object",
properties: {
location: {
title: "Geographic Location",
description:
"The geographic location code (US for United States, for example)",
type: "string",
default: "US",
},
},
},
outputSchema: {
type: "object",
properties: {
result: {
title: "Trends",
type: "object",
},
},
},
} as NodeDescriberResult);
export default service(describe, getTrends);