实现采集器模块

- 添加采集器类型定义 (collector.ts)
- 实现采集器基类 (base.collector.ts)
- 实现 API 采集器 (api.collector.ts)
- 实现 Playwright 网页采集器 (playwright.collector.ts)
- 实现 RSS 采集器 (rss.collector.ts)
- 创建采集器工厂 (collector.factory.ts)
- 实现采集服务 (collector.service.ts)
- 安装 rss-parser 依赖

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
hughhuangandClaude Opus 4.5 committed 2026-02-03 23:50:31 +08:00
1 parent b8791ee556
commit fe7714a3a6
10 files changed
+703

No files matched your search

+144
View File
@@ -0,0 +1,144 @@
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<CollectionResult> {
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 options: RequestInit = {
method: this.apiConfig.method || 'GET',
headers: {
'User-Agent': 'News-Aggregator/1.0',
...this.apiConfig.headers,
},
};
if (this.apiConfig.body && this.apiConfig.method === 'POST') {
options.body = JSON.stringify(this.apiConfig.body);
options.headers = {
...options.headers,
'Content-Type': 'application/json',
};
}
// 发送请求
const response = await fetch(url.toString(), options);
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;
}
}