import { BaseCollector } from './base.collector'; import { CollectorType, CollectionResult, CollectedArticle, ApiCollectorConfig, } from '../types/collector'; import logger from '../utils/logger'; export class ApiCollector extends BaseCollector { private apiConfig: ApiCollectorConfig; constructor(config: ApiCollectorConfig, sourceId: number) { super(config, sourceId); this.apiConfig = config; } async collect(): Promise { try { logger.info(`API采集器开始采集: ${this.apiConfig.url}`); // 构建请求 URL const url = new URL(this.apiConfig.url); if (this.apiConfig.params) { Object.entries(this.apiConfig.params).forEach(([key, value]) => { url.searchParams.append(key, String(value)); }); } // 设置超时控制 const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), 30000); const options: RequestInit = { method: this.apiConfig.method || 'GET', headers: { 'User-Agent': 'News-Aggregator/1.0', ...this.apiConfig.headers, }, signal: controller.signal, }; if (this.apiConfig.body && this.apiConfig.method === 'POST') { options.body = JSON.stringify(this.apiConfig.body); options.headers = { ...options.headers, 'Content-Type': 'application/json', }; } // 发送请求 let response: Response; try { response = await fetch(url.toString(), options); } finally { clearTimeout(timeout); } if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`); } const data = await response.json(); // 提取数据 let items: any[] = []; let rawItems = data; if (this.apiConfig.dataPath) { rawItems = this.getNestedValue(data, this.apiConfig.dataPath); } if (Array.isArray(rawItems)) { items = rawItems; } else if (rawItems) { items = [rawItems]; } // 映射数据 const articles: CollectedArticle[] = items.map((item: any) => { const article: CollectedArticle = { title: this.getNestedValue(item, this.apiConfig.mapping.title) || '', rawData: item, }; if (this.apiConfig.mapping.content) { article.content = this.getNestedValue(item, this.apiConfig.mapping.content); } if (this.apiConfig.mapping.url) { article.url = this.getNestedValue(item, this.apiConfig.mapping.url); } if (this.apiConfig.mapping.publishedAt) { const dateValue = this.getNestedValue(item, this.apiConfig.mapping.publishedAt); article.publishedAt = this.parseDate(dateValue); } return article; }); logger.info(`API采集器完成,采集到 ${articles.length} 条资讯`); return { articles, success: true, }; } catch (error) { logger.error('API采集器失败', error); return { articles: [], success: false, error: error instanceof Error ? error.message : 'Unknown error', }; } } validateConfig(): boolean { return !!( this.apiConfig.url && this.apiConfig.mapping && this.apiConfig.mapping.title ); } getType(): CollectorType { return 'api'; } private getNestedValue(obj: any, path: string): any { return path.split('.').reduce((current, key) => current?.[key], obj); } private parseDate(value: any): Date | undefined { if (!value) return undefined; // Unix 时间戳(秒) if (typeof value === 'number' && value > 1000000000 && value < 10000000000) { return new Date(value * 1000); } // Unix 时间戳(毫秒) if (typeof value === 'number' && value > 1000000000000) { return new Date(value); } // ISO 字符串 if (typeof value === 'string') { const date = new Date(value); return isNaN(date.getTime()) ? undefined : date; } return undefined; } }