refactor: catch potential error; add comments

This commit is contained in:
Ayo Ayco 2025-08-23 20:43:51 +02:00
parent e751a4e5d3
commit 5039f9c6af

View file

@ -8,36 +8,58 @@ import App from '../layouts/App.astro'
import Library from '../components/Library.astro' import Library from '../components/Library.astro'
import Footer from '../components/Footer.astro' import Footer from '../components/Footer.astro'
// Initialize Redis client
const client = createClient() const client = createClient()
client.on('error', (err) => console.error('Redis Client Error', err)) client.on('error', (err) => console.error('Redis Client Error', err))
await client.connect() await client.connect()
// Disable prerendering for dynamic content
export const prerender = false export const prerender = false
// Get URL parameter from query string
let url = Astro.url.searchParams.get('url') let url = Astro.url.searchParams.get('url')
let article: ArticleData | null = { url: '/' } let article: ArticleData | null = { url: '/' }
// Handle redirect loops by extracting URL from nested parameters
while (url?.startsWith(Astro.url.origin)) { while (url?.startsWith(Astro.url.origin)) {
url = new URL(url).searchParams.get('url') try {
// Parse the URL to extract search parameters
const parsedUrl = new URL(url)
url = parsedUrl.searchParams.get('url')
} catch {
// If URL parsing fails, break the loop
console.error('Failed to parse URL:', url)
break
}
} }
// Process article extraction only if a valid URL is provided
if (url && url !== '/' && url !== '') { if (url && url !== '/' && url !== '') {
const exists = await client.exists('cozy:url:' + url) const cacheKey = 'cozy:url:' + url
// try cache
try {
// Check if article exists in Redis cache
const exists = await client.exists(cacheKey)
if (exists) { if (exists) {
article = (await client.json.get('cozy:url:' + url)) as ArticleData // Retrieve cached article data
article = (await client.json.get(cacheKey)) as ArticleData
console.log('>>> Using cached content', article.url) console.log('>>> Using cached content', article.url)
} else { } else {
try { // Fetch article from the web
article = await extract(url) article = await extract(url)
console.log('>>> Using fetched content', article?.url) console.log('>>> Using fetched content', article?.url)
if (article !== null) {
// cache via redis if (article !== null && article.url) {
await client.json.set('cozy:url:' + url, '$', article as RedisJSON) // Cache the fetched article in Redis
await client.json.set(cacheKey, '$', article as RedisJSON)
console.log('>>> Added to cache', article.url) console.log('>>> Added to cache', article.url)
} }
} catch {
article = null
} }
} catch (error) {
// Log error and continue with null article
console.error('Error processing article:', error)
article = null
} }
} }
--- ---