Created
February 11, 2025 04:50
-
-
Save ZaymonFC/c40663ff4d4314885cbe05d5e89ac8f0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface RSSItem { | |
title: string; | |
link: string; | |
description: string; | |
pubDate: string; | |
guid: string; | |
} | |
interface RSSFeed { | |
title: string; | |
description: string; | |
link: string; | |
items: RSSItem[]; | |
} | |
const extractTextContent = (element: Element | null): string => | |
element?.textContent || ''; | |
const parseRSSItem = (item: Element): RSSItem => ({ | |
title: extractTextContent(item.querySelector('title')), | |
link: extractTextContent(item.querySelector('link')), | |
description: extractTextContent(item.querySelector('description')), | |
pubDate: extractTextContent(item.querySelector('pubDate')), | |
guid: extractTextContent(item.querySelector('guid')) | |
}); | |
const buildRSSFeed = (doc: Document): RSSFeed => ({ | |
title: extractTextContent(doc.querySelector('channel > title')), | |
description: extractTextContent(doc.querySelector('channel > description')), | |
link: extractTextContent(doc.querySelector('channel > link')), | |
items: Array.from(doc.querySelectorAll('item')).map(parseRSSItem) | |
}); | |
/** | |
* Fetches and parses an RSS feed from the provided URL. | |
*/ | |
export default async ({ | |
event: { | |
data: { request }, | |
}, | |
}: any) => { | |
try { | |
const { args: [url] = [] } = await request.json(); | |
if (!url) { | |
return new Response( | |
JSON.stringify({ error: 'RSS URL is required' }), | |
{ | |
status: 400, | |
headers: { 'Content-Type': 'application/json' } | |
} | |
); | |
} | |
const response = await fetch(url); | |
const text = await response.text(); | |
const doc = new DOMParser().parseFromString(text, 'text/xml'); | |
const feed = buildRSSFeed(doc); | |
return new Response( | |
JSON.stringify(feed), | |
{ headers: { 'Content-Type': 'application/json' }} | |
); | |
} catch (error: unknown) { | |
const message = error instanceof Error ? error.message : 'An unknown error occurred'; | |
return new Response( | |
JSON.stringify({ error: message }), | |
{ | |
status: 500, | |
headers: { 'Content-Type': 'application/json' } | |
} | |
); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment