diff --git a/services/database.ts b/services/database.ts index 70836f9..51cba6d 100644 --- a/services/database.ts +++ b/services/database.ts @@ -272,24 +272,42 @@ export interface EpisodeWithFeedInfo { export async function saveFeed( feed: Omit, ): Promise { - const id = crypto.randomUUID(); - const createdAt = new Date().toISOString(); - try { - const stmt = db.prepare( - "INSERT OR REPLACE INTO feeds (id, url, title, description, last_updated, created_at, active) VALUES (?, ?, ?, ?, ?, ?, ?)", - ); - stmt.run( - id, - feed.url, - feed.title || null, - feed.description || null, - feed.lastUpdated || null, - createdAt, - feed.active !== undefined ? (feed.active ? 1 : 0) : 1, // Default to active=1 if not specified - ); - - return id; + // Check if feed already exists + const existingFeed = await getFeedByUrl(feed.url); + + if (existingFeed) { + // Update existing feed + const updateStmt = db.prepare( + "UPDATE feeds SET title = ?, description = ?, last_updated = ?, active = ? WHERE url = ?", + ); + updateStmt.run( + feed.title || null, + feed.description || null, + feed.lastUpdated || null, + feed.active !== undefined ? (feed.active ? 1 : 0) : 1, + feed.url, + ); + return existingFeed.id; + } else { + // Create new feed + const id = crypto.randomUUID(); + const createdAt = new Date().toISOString(); + + const insertStmt = db.prepare( + "INSERT INTO feeds (id, url, title, description, last_updated, created_at, active) VALUES (?, ?, ?, ?, ?, ?, ?)", + ); + insertStmt.run( + id, + feed.url, + feed.title || null, + feed.description || null, + feed.lastUpdated || null, + createdAt, + feed.active !== undefined ? (feed.active ? 1 : 0) : 1, + ); + return id; + } } catch (error) { console.error("Error saving feed:", error); throw error;