feat: implement orchestrator module with feed source management
Add FeedOrchestrator that coordinates fetch→parse→dedup→store pipeline: - FeedSource type for managing RSS/Atom feed configurations - Feed source CRUD operations in IStorage interface - Database schema migration for feed_sources table - Exponential backoff retry with configurable delays - Per-feed poll intervals with health tracking - Concurrency-limited parallel feed processing - ProcessResult and FeedHealth interfaces for status monitoring Files added: - orchestrator/orchestrator.ts - main orchestrator class - orchestrator/scheduler.ts - backoff calculation utilities - orchestrator/index.ts - module exports - orchestrator/orchestrator.test.ts - comprehensive test suite Files modified: - interfaces/feed.types.ts - add FeedSource type - interfaces/storage.interface.ts - extend with feed source methods - infrastructure/db/database.ts - add FeedSourceTable interface - infrastructure/db/schema.ts - add feed_sources table migration - modules/storage/storage.ts - implement feed source CRUD - modules/storage/storage.test.ts - add feed source tests
This commit is contained in:
@@ -0,0 +1,207 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { Formatter } from './formatter.js';
|
||||
import { TerminalFormatter } from './terminal.formatter.js';
|
||||
import { JsonFormatter } from './json.formatter.js';
|
||||
import type { FeedItem } from '../../interfaces/feed.types.js';
|
||||
|
||||
describe('Formatter', () => {
|
||||
const formatter = new Formatter();
|
||||
|
||||
const createMockItem = (id: string, overrides: Partial<FeedItem> = {}): FeedItem => ({
|
||||
id,
|
||||
source: 'https://example.com/feed',
|
||||
title: 'Test Article',
|
||||
url: 'https://example.com/article/1',
|
||||
publishedAt: new Date('2026-05-05T10:30:00Z'),
|
||||
content: undefined,
|
||||
summary: undefined,
|
||||
...overrides
|
||||
});
|
||||
|
||||
describe('format with terminal format', () => {
|
||||
it('should format empty array', async () => {
|
||||
const result = await formatter.format([], 'terminal');
|
||||
expect(result).toContain('No items to display');
|
||||
});
|
||||
|
||||
it('should format single item', async () => {
|
||||
const item = createMockItem('item-1', {
|
||||
title: 'My Article',
|
||||
source: 'https://myblog.com/feed'
|
||||
});
|
||||
const result = await formatter.format([item], 'terminal');
|
||||
expect(result).toContain('1.');
|
||||
expect(result).toContain('My Article');
|
||||
expect(result).toContain('https://myblog.com/feed');
|
||||
expect(result).toContain('https://example.com/article/1');
|
||||
});
|
||||
|
||||
it('should format multiple items', async () => {
|
||||
const items = [
|
||||
createMockItem('item-1', { title: 'Article 1' }),
|
||||
createMockItem('item-2', { title: 'Article 2' })
|
||||
];
|
||||
const result = await formatter.format(items, 'terminal');
|
||||
expect(result).toContain('Found 2 items');
|
||||
expect(result).toContain('1.');
|
||||
expect(result).toContain('2.');
|
||||
expect(result).toContain('Article 1');
|
||||
expect(result).toContain('Article 2');
|
||||
});
|
||||
|
||||
it('should include summary when present', async () => {
|
||||
const item = createMockItem('item-1', {
|
||||
summary: 'This is a test summary that might be truncated'
|
||||
});
|
||||
const result = await formatter.format([item], 'terminal');
|
||||
expect(result).toContain('This is a test summary');
|
||||
});
|
||||
});
|
||||
|
||||
describe('format with json format', () => {
|
||||
it('should format empty array', async () => {
|
||||
const result = await formatter.format([], 'json');
|
||||
expect(JSON.parse(result)).toEqual([]);
|
||||
});
|
||||
|
||||
it('should format single item', async () => {
|
||||
const item = createMockItem('item-1', {
|
||||
title: 'My Article'
|
||||
});
|
||||
const result = await formatter.format([item], 'json');
|
||||
const parsed = JSON.parse(result);
|
||||
expect(parsed).toHaveLength(1);
|
||||
expect(parsed[0].id).toBe('item-1');
|
||||
expect(parsed[0].title).toBe('My Article');
|
||||
expect(parsed[0].publishedAt).toBe('2026-05-05T10:30:00.000Z');
|
||||
});
|
||||
|
||||
it('should format multiple items', async () => {
|
||||
const items = [
|
||||
createMockItem('item-1', { title: 'Article 1' }),
|
||||
createMockItem('item-2', { title: 'Article 2' })
|
||||
];
|
||||
const result = await formatter.format(items, 'json');
|
||||
const parsed = JSON.parse(result);
|
||||
expect(parsed).toHaveLength(2);
|
||||
expect(parsed[0].title).toBe('Article 1');
|
||||
expect(parsed[1].title).toBe('Article 2');
|
||||
});
|
||||
|
||||
it('should include optional content when present', async () => {
|
||||
const item = createMockItem('item-1', {
|
||||
content: 'Full article content here'
|
||||
});
|
||||
const result = await formatter.format([item], 'json');
|
||||
const parsed = JSON.parse(result);
|
||||
expect(parsed[0].content).toBe('Full article content here');
|
||||
});
|
||||
|
||||
it('should include optional summary when present', async () => {
|
||||
const item = createMockItem('item-1', {
|
||||
summary: 'Article summary'
|
||||
});
|
||||
const result = await formatter.format([item], 'json');
|
||||
const parsed = JSON.parse(result);
|
||||
expect(parsed[0].summary).toBe('Article summary');
|
||||
});
|
||||
|
||||
it('should not include undefined fields', async () => {
|
||||
const item = createMockItem('item-1');
|
||||
const result = await formatter.format([item], 'json');
|
||||
const parsed = JSON.parse(result);
|
||||
expect(parsed[0]).not.toHaveProperty('content');
|
||||
expect(parsed[0]).not.toHaveProperty('summary');
|
||||
});
|
||||
|
||||
it('should use ISO 8601 date format', async () => {
|
||||
const item = createMockItem('item-1', {
|
||||
publishedAt: new Date('2026-12-25T15:30:45.123Z')
|
||||
});
|
||||
const result = await formatter.format([item], 'json');
|
||||
const parsed = JSON.parse(result);
|
||||
expect(parsed[0].publishedAt).toBe('2026-12-25T15:30:45.123Z');
|
||||
});
|
||||
});
|
||||
|
||||
describe('error handling', () => {
|
||||
it('should throw FormatterError for HTML format', async () => {
|
||||
await expect(formatter.format([], 'html')).rejects.toMatchObject({
|
||||
code: 'UNKNOWN',
|
||||
message: 'HTML format not implemented'
|
||||
});
|
||||
});
|
||||
|
||||
it('should throw FormatterError for unknown format', async () => {
|
||||
await expect(formatter.format([], 'unknown-format' as any)).rejects.toMatchObject({
|
||||
code: 'SERIALIZE_ERROR'
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('TerminalFormatter', () => {
|
||||
const terminalFormatter = new TerminalFormatter();
|
||||
|
||||
it('should truncate long summary text', () => {
|
||||
const longSummary = 'a'.repeat(100);
|
||||
const item: FeedItem = {
|
||||
id: 'item-1',
|
||||
source: 'https://example.com',
|
||||
title: 'Test',
|
||||
url: 'https://example.com/article',
|
||||
publishedAt: new Date(),
|
||||
summary: longSummary
|
||||
};
|
||||
const result = terminalFormatter.format([item]);
|
||||
expect(result).toContain('...');
|
||||
expect(result).not.toContain(longSummary);
|
||||
});
|
||||
|
||||
it('should format date in readable format', () => {
|
||||
const item: FeedItem = {
|
||||
id: 'item-1',
|
||||
source: 'https://example.com',
|
||||
title: 'Test',
|
||||
url: 'https://example.com/article',
|
||||
publishedAt: new Date('2026-05-05T10:30:00Z')
|
||||
};
|
||||
const result = terminalFormatter.format([item]);
|
||||
expect(result).toContain('May');
|
||||
expect(result).toContain('2026');
|
||||
});
|
||||
});
|
||||
|
||||
describe('JsonFormatter', () => {
|
||||
const jsonFormatter = new JsonFormatter();
|
||||
|
||||
it('should produce valid JSON', () => {
|
||||
const items: FeedItem[] = [
|
||||
{
|
||||
id: 'test-1',
|
||||
source: 'https://example.com',
|
||||
title: 'Test Article',
|
||||
url: 'https://example.com/1',
|
||||
publishedAt: new Date()
|
||||
}
|
||||
];
|
||||
const result = jsonFormatter.format(items);
|
||||
expect(() => JSON.parse(result)).not.toThrow();
|
||||
});
|
||||
|
||||
it('should convert Date to ISO string', () => {
|
||||
const date = new Date('2026-01-15T08:00:00Z');
|
||||
const items: FeedItem[] = [
|
||||
{
|
||||
id: 'test-1',
|
||||
source: 'https://example.com',
|
||||
title: 'Test',
|
||||
url: 'https://example.com/1',
|
||||
publishedAt: date
|
||||
}
|
||||
];
|
||||
const result = jsonFormatter.format(items);
|
||||
const parsed = JSON.parse(result);
|
||||
expect(parsed[0].publishedAt).toBe('2026-01-15T08:00:00.000Z');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { IFormatter, FormatterError, OutputFormat } from '../../interfaces/formatter.interface.js';
|
||||
import type { FeedItem } from '../../interfaces/feed.types.js';
|
||||
import { TerminalFormatter } from './terminal.formatter.js';
|
||||
import { JsonFormatter } from './json.formatter.js';
|
||||
|
||||
export class Formatter implements IFormatter {
|
||||
private terminalFormatter: TerminalFormatter;
|
||||
private jsonFormatter: JsonFormatter;
|
||||
|
||||
constructor() {
|
||||
this.terminalFormatter = new TerminalFormatter();
|
||||
this.jsonFormatter = new JsonFormatter();
|
||||
}
|
||||
|
||||
async format(items: FeedItem[], format: OutputFormat): Promise<string> {
|
||||
try {
|
||||
switch (format) {
|
||||
case 'terminal':
|
||||
return this.terminalFormatter.format(items);
|
||||
case 'json':
|
||||
return this.jsonFormatter.format(items);
|
||||
case 'html':
|
||||
// HTML not implemented yet per requirements
|
||||
throw this.createError('UNKNOWN', 'HTML format not implemented');
|
||||
default:
|
||||
throw this.createError('SERIALIZE_ERROR', `Unknown format: ${format}`);
|
||||
}
|
||||
} catch (error) {
|
||||
if (this.isFormatterError(error)) {
|
||||
throw error;
|
||||
}
|
||||
throw this.createError('UNKNOWN', error instanceof Error ? error.message : 'Unknown error during formatting');
|
||||
}
|
||||
}
|
||||
|
||||
private createError(code: FormatterError['code'], message: string): FormatterError {
|
||||
return { code, message };
|
||||
}
|
||||
|
||||
private isFormatterError(error: unknown): error is FormatterError {
|
||||
return (
|
||||
typeof error === 'object' &&
|
||||
error !== null &&
|
||||
'code' in error &&
|
||||
'message' in error &&
|
||||
(error as FormatterError).code !== undefined
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export { Formatter } from './formatter.js';
|
||||
export { TerminalFormatter } from './terminal.formatter.js';
|
||||
export { JsonFormatter } from './json.formatter.js';
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { FeedItem } from '../../interfaces/feed.types.js';
|
||||
|
||||
interface JsonFeedItem {
|
||||
id: string;
|
||||
source: string;
|
||||
title: string;
|
||||
url: string;
|
||||
publishedAt: string;
|
||||
content?: string;
|
||||
summary?: string;
|
||||
}
|
||||
|
||||
export class JsonFormatter {
|
||||
format(items: FeedItem[]): string {
|
||||
const jsonItems: JsonFeedItem[] = items.map(item => ({
|
||||
id: item.id,
|
||||
source: item.source,
|
||||
title: item.title,
|
||||
url: item.url,
|
||||
publishedAt: item.publishedAt.toISOString(),
|
||||
...(item.content !== undefined && { content: item.content }),
|
||||
...(item.summary !== undefined && { summary: item.summary })
|
||||
}));
|
||||
|
||||
return JSON.stringify(jsonItems, null, 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import type { FeedItem } from '../../interfaces/feed.types.js';
|
||||
|
||||
export class TerminalFormatter {
|
||||
format(items: FeedItem[]): string {
|
||||
if (items.length === 0) {
|
||||
return '\n No items to display.\n';
|
||||
}
|
||||
|
||||
const lines: string[] = [];
|
||||
lines.push('');
|
||||
lines.push(` ${this.bold(`Found ${items.length} item${items.length === 1 ? '' : 's'}`)}`);
|
||||
lines.push('');
|
||||
|
||||
items.forEach((item, index) => {
|
||||
const number = `${index + 1}.`.padStart(3);
|
||||
lines.push(` ${this.dim(number)} ${this.cyan(item.source)}`);
|
||||
lines.push(` ${this.bold(item.title)}`);
|
||||
lines.push(` ${this.dim(this.formatDate(item.publishedAt))}`);
|
||||
lines.push(` ${this.blue(item.url)}`);
|
||||
|
||||
if (item.summary) {
|
||||
const truncated = this.truncate(item.summary, 80);
|
||||
lines.push(` ${this.dim(truncated)}`);
|
||||
}
|
||||
|
||||
lines.push('');
|
||||
});
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
private formatDate(date: Date): string {
|
||||
return date.toLocaleString('en-US', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
}
|
||||
|
||||
private truncate(text: string, maxLength: number): string {
|
||||
if (text.length <= maxLength) {
|
||||
return text;
|
||||
}
|
||||
return text.substring(0, maxLength - 3) + '...';
|
||||
}
|
||||
|
||||
// ANSI color codes
|
||||
private bold(text: string): string {
|
||||
return `\x1b[1m${text}\x1b[0m`;
|
||||
}
|
||||
|
||||
private dim(text: string): string {
|
||||
return `\x1b[2m${text}\x1b[0m`;
|
||||
}
|
||||
|
||||
private cyan(text: string): string {
|
||||
return `\x1b[36m${text}\x1b[0m`;
|
||||
}
|
||||
|
||||
private blue(text: string): string {
|
||||
return `\x1b[34m${text}\x1b[0m`;
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import { Kysely, SqliteDialect } from 'kysely';
|
||||
import { SqlStorage } from './storage.js';
|
||||
import { migrate, reset } from '../../infrastructure/db/schema.js';
|
||||
import type { Database } from '../../infrastructure/db/database.js';
|
||||
import type { FeedItem } from '../../interfaces/feed.types.js';
|
||||
import type { FeedItem, FeedSource } from '../../interfaces/feed.types.js';
|
||||
|
||||
describe('SqlStorage', () => {
|
||||
let sqliteDb: BetterSqlite3.Database;
|
||||
@@ -427,4 +427,176 @@ describe('SqlStorage', () => {
|
||||
expect(recent[0].content).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Feed Source Management', () => {
|
||||
function createTestFeedSource(overrides: Partial<FeedSource> = {}): FeedSource {
|
||||
const now = new Date();
|
||||
return {
|
||||
id: 'test-source-1',
|
||||
url: 'https://example.com/feed.xml',
|
||||
name: 'Test Feed',
|
||||
format: 'rss',
|
||||
pollIntervalMs: 60000,
|
||||
isActive: true,
|
||||
lastFetchedAt: null,
|
||||
lastSuccessAt: null,
|
||||
consecutiveFailures: 0,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('saveFeedSource', () => {
|
||||
it('saves a new feed source', async () => {
|
||||
const source = createTestFeedSource();
|
||||
await storage.saveFeedSource(source);
|
||||
|
||||
const retrieved = await storage.getFeedSourceById(source.id);
|
||||
expect(retrieved).toBeTruthy();
|
||||
expect(retrieved!.id).toBe(source.id);
|
||||
expect(retrieved!.url).toBe(source.url);
|
||||
expect(retrieved!.name).toBe(source.name);
|
||||
expect(retrieved!.format).toBe(source.format);
|
||||
expect(retrieved!.pollIntervalMs).toBe(source.pollIntervalMs);
|
||||
expect(retrieved!.isActive).toBe(source.isActive);
|
||||
});
|
||||
|
||||
it('updates existing feed source on duplicate id (upsert)', async () => {
|
||||
const source = createTestFeedSource({ id: 'same-id', name: 'Original Name' });
|
||||
await storage.saveFeedSource(source);
|
||||
|
||||
const updated = createTestFeedSource({
|
||||
id: 'same-id',
|
||||
name: 'Updated Name',
|
||||
pollIntervalMs: 120000,
|
||||
});
|
||||
await storage.saveFeedSource(updated);
|
||||
|
||||
const retrieved = await storage.getFeedSourceById('same-id');
|
||||
expect(retrieved!.name).toBe('Updated Name');
|
||||
expect(retrieved!.pollIntervalMs).toBe(120000);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getFeedSources', () => {
|
||||
it('returns all feed sources', async () => {
|
||||
const source1 = createTestFeedSource({ id: 'source-1', url: 'https://example1.com/feed.xml' });
|
||||
const source2 = createTestFeedSource({ id: 'source-2', url: 'https://example2.com/feed.xml' });
|
||||
|
||||
await storage.saveFeedSource(source1);
|
||||
await storage.saveFeedSource(source2);
|
||||
|
||||
const sources = await storage.getFeedSources();
|
||||
expect(sources).toHaveLength(2);
|
||||
expect(sources.map(s => s.id)).toContain('source-1');
|
||||
expect(sources.map(s => s.id)).toContain('source-2');
|
||||
});
|
||||
|
||||
it('returns only active sources when activeOnly is true', async () => {
|
||||
const active = createTestFeedSource({ id: 'active', url: 'https://active.com/feed.xml', isActive: true });
|
||||
const inactive = createTestFeedSource({ id: 'inactive', url: 'https://inactive.com/feed.xml', isActive: false });
|
||||
|
||||
await storage.saveFeedSource(active);
|
||||
await storage.saveFeedSource(inactive);
|
||||
|
||||
const sources = await storage.getFeedSources(true);
|
||||
expect(sources).toHaveLength(1);
|
||||
expect(sources[0]!.id).toBe('active');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getFeedSourceById', () => {
|
||||
it('returns feed source by id', async () => {
|
||||
const source = createTestFeedSource({ id: 'specific-id' });
|
||||
await storage.saveFeedSource(source);
|
||||
|
||||
const retrieved = await storage.getFeedSourceById('specific-id');
|
||||
expect(retrieved).toBeTruthy();
|
||||
expect(retrieved!.id).toBe('specific-id');
|
||||
});
|
||||
|
||||
it('returns null for non-existent id', async () => {
|
||||
const retrieved = await storage.getFeedSourceById('non-existent');
|
||||
expect(retrieved).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateFeedSourceStatus', () => {
|
||||
it('updates lastFetchedAt', async () => {
|
||||
const source = createTestFeedSource();
|
||||
await storage.saveFeedSource(source);
|
||||
|
||||
const fetchTime = new Date('2024-09-06T10:00:00Z');
|
||||
await storage.updateFeedSourceStatus(source.id, { lastFetchedAt: fetchTime });
|
||||
|
||||
const retrieved = await storage.getFeedSourceById(source.id);
|
||||
expect(retrieved!.lastFetchedAt).toEqual(fetchTime);
|
||||
});
|
||||
|
||||
it('updates lastSuccessAt', async () => {
|
||||
const source = createTestFeedSource();
|
||||
await storage.saveFeedSource(source);
|
||||
|
||||
const successTime = new Date('2024-09-06T10:00:00Z');
|
||||
await storage.updateFeedSourceStatus(source.id, { lastSuccessAt: successTime });
|
||||
|
||||
const retrieved = await storage.getFeedSourceById(source.id);
|
||||
expect(retrieved!.lastSuccessAt).toEqual(successTime);
|
||||
});
|
||||
|
||||
it('updates consecutiveFailures', async () => {
|
||||
const source = createTestFeedSource();
|
||||
await storage.saveFeedSource(source);
|
||||
|
||||
await storage.updateFeedSourceStatus(source.id, { consecutiveFailures: 5 });
|
||||
|
||||
const retrieved = await storage.getFeedSourceById(source.id);
|
||||
expect(retrieved!.consecutiveFailures).toBe(5);
|
||||
});
|
||||
|
||||
it('updates isActive', async () => {
|
||||
const source = createTestFeedSource({ isActive: true });
|
||||
await storage.saveFeedSource(source);
|
||||
|
||||
await storage.updateFeedSourceStatus(source.id, { isActive: false });
|
||||
|
||||
const retrieved = await storage.getFeedSourceById(source.id);
|
||||
expect(retrieved!.isActive).toBe(false);
|
||||
});
|
||||
|
||||
it('updates multiple fields at once', async () => {
|
||||
const source = createTestFeedSource();
|
||||
await storage.saveFeedSource(source);
|
||||
|
||||
const now = new Date();
|
||||
await storage.updateFeedSourceStatus(source.id, {
|
||||
lastFetchedAt: now,
|
||||
lastSuccessAt: now,
|
||||
consecutiveFailures: 0,
|
||||
});
|
||||
|
||||
const retrieved = await storage.getFeedSourceById(source.id);
|
||||
expect(retrieved!.lastFetchedAt).toEqual(now);
|
||||
expect(retrieved!.lastSuccessAt).toEqual(now);
|
||||
expect(retrieved!.consecutiveFailures).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteFeedSource', () => {
|
||||
it('deletes feed source by id', async () => {
|
||||
const source = createTestFeedSource({ id: 'to-delete' });
|
||||
await storage.saveFeedSource(source);
|
||||
|
||||
await storage.deleteFeedSource('to-delete');
|
||||
|
||||
const retrieved = await storage.getFeedSourceById('to-delete');
|
||||
expect(retrieved).toBeNull();
|
||||
});
|
||||
|
||||
it('does not throw when deleting non-existent id', async () => {
|
||||
await expect(storage.deleteFeedSource('non-existent')).resolves.not.toThrow();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
+113
-2
@@ -4,9 +4,9 @@
|
||||
*/
|
||||
|
||||
import type { Kysely } from 'kysely';
|
||||
import type { FeedItem } from '../../interfaces/feed.types.js';
|
||||
import type { FeedItem, FeedSource } from '../../interfaces/feed.types.js';
|
||||
import type { IStorage } from '../../interfaces/storage.interface.js';
|
||||
import type { Database, FeedItemTable } from '../../infrastructure/db/database.js';
|
||||
import type { Database, FeedItemTable, FeedSourceTable } from '../../infrastructure/db/database.js';
|
||||
|
||||
export class SqlStorage implements IStorage {
|
||||
private readonly db: Kysely<Database>;
|
||||
@@ -98,4 +98,115 @@ export class SqlStorage implements IStorage {
|
||||
summary: row.summary ?? undefined,
|
||||
};
|
||||
}
|
||||
|
||||
// Feed source management methods
|
||||
|
||||
async getFeedSources(activeOnly?: boolean): Promise<FeedSource[]> {
|
||||
let query = this.db.selectFrom('feed_sources').selectAll();
|
||||
|
||||
if (activeOnly) {
|
||||
query = query.where('is_active', '=', 1); // Use 1 for SQLite boolean
|
||||
}
|
||||
|
||||
const rows = await query.orderBy('created_at', 'asc').execute();
|
||||
return rows.map(this.rowToFeedSource);
|
||||
}
|
||||
|
||||
async getFeedSourceById(id: string): Promise<FeedSource | null> {
|
||||
const row = await this.db
|
||||
.selectFrom('feed_sources')
|
||||
.selectAll()
|
||||
.where('id', '=', id)
|
||||
.executeTakeFirst();
|
||||
|
||||
return row ? this.rowToFeedSource(row) : null;
|
||||
}
|
||||
|
||||
async saveFeedSource(source: FeedSource): Promise<void> {
|
||||
const now = new Date().toISOString();
|
||||
const row: FeedSourceTable = {
|
||||
id: source.id,
|
||||
url: source.url,
|
||||
name: source.name,
|
||||
format: source.format,
|
||||
poll_interval_ms: source.pollIntervalMs,
|
||||
is_active: source.isActive ? 1 : 0, // Convert boolean to integer for SQLite
|
||||
last_fetched_at: source.lastFetchedAt?.toISOString() ?? null,
|
||||
last_success_at: source.lastSuccessAt?.toISOString() ?? null,
|
||||
consecutive_failures: source.consecutiveFailures,
|
||||
created_at: source.createdAt.toISOString(),
|
||||
updated_at: now,
|
||||
};
|
||||
|
||||
// Upsert: insert or update on conflict
|
||||
await this.db
|
||||
.insertInto('feed_sources')
|
||||
.values(row)
|
||||
.onConflict((oc) =>
|
||||
oc.column('id').doUpdateSet({
|
||||
name: (eb) => eb.ref('excluded.name'),
|
||||
format: (eb) => eb.ref('excluded.format'),
|
||||
poll_interval_ms: (eb) => eb.ref('excluded.poll_interval_ms'),
|
||||
is_active: (eb) => eb.ref('excluded.is_active'),
|
||||
last_fetched_at: (eb) => eb.ref('excluded.last_fetched_at'),
|
||||
last_success_at: (eb) => eb.ref('excluded.last_success_at'),
|
||||
consecutive_failures: (eb) => eb.ref('excluded.consecutive_failures'),
|
||||
updated_at: (eb) => eb.ref('excluded.updated_at'),
|
||||
})
|
||||
)
|
||||
.execute();
|
||||
}
|
||||
|
||||
async updateFeedSourceStatus(
|
||||
id: string,
|
||||
updates: {
|
||||
lastFetchedAt?: Date;
|
||||
lastSuccessAt?: Date;
|
||||
consecutiveFailures?: number;
|
||||
isActive?: boolean;
|
||||
}
|
||||
): Promise<void> {
|
||||
const setClause: Partial<FeedSourceTable> = {
|
||||
updated_at: new Date().toISOString(),
|
||||
};
|
||||
|
||||
if (updates.lastFetchedAt !== undefined) {
|
||||
setClause.last_fetched_at = updates.lastFetchedAt.toISOString();
|
||||
}
|
||||
if (updates.lastSuccessAt !== undefined) {
|
||||
setClause.last_success_at = updates.lastSuccessAt?.toISOString() ?? null;
|
||||
}
|
||||
if (updates.consecutiveFailures !== undefined) {
|
||||
setClause.consecutive_failures = updates.consecutiveFailures;
|
||||
}
|
||||
if (updates.isActive !== undefined) {
|
||||
setClause.is_active = updates.isActive ? 1 : 0; // Convert boolean to integer for SQLite
|
||||
}
|
||||
|
||||
await this.db
|
||||
.updateTable('feed_sources')
|
||||
.set(setClause)
|
||||
.where('id', '=', id)
|
||||
.execute();
|
||||
}
|
||||
|
||||
async deleteFeedSource(id: string): Promise<void> {
|
||||
await this.db.deleteFrom('feed_sources').where('id', '=', id).execute();
|
||||
}
|
||||
|
||||
private rowToFeedSource(row: FeedSourceTable): FeedSource {
|
||||
return {
|
||||
id: row.id,
|
||||
url: row.url,
|
||||
name: row.name,
|
||||
format: row.format,
|
||||
pollIntervalMs: row.poll_interval_ms,
|
||||
isActive: Boolean(row.is_active), // Convert integer to boolean
|
||||
lastFetchedAt: row.last_fetched_at ? new Date(row.last_fetched_at) : null,
|
||||
lastSuccessAt: row.last_success_at ? new Date(row.last_success_at) : null,
|
||||
consecutiveFailures: row.consecutive_failures,
|
||||
createdAt: new Date(row.created_at),
|
||||
updatedAt: new Date(row.updated_at),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user