实现采集器模块

- 添加采集器类型定义 (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

+155
View File
@@ -0,0 +1,155 @@
import prisma from '../config/database';
import { CollectorFactory } from '../collectors/collector.factory';
import { CollectorType } from '../types/collector';
import logger from '../utils/logger';
export class CollectorService {
/**
* 执行单个数据源的采集
*/
async collectSource(sourceId: number): Promise<void> {
const startTime = Date.now();
let articlesCount = 0;
let status: 'success' | 'failed' = 'success';
let errorMessage: string | undefined;
try {
// 查询数据源
const source = await prisma.source.findUnique({
where: { id: sourceId },
});
if (!source) {
throw new Error(`Source ${sourceId} not found`);
}
if (!source.enabled) {
logger.info(`数据源 ${source.name} 已禁用,跳过采集`);
return;
}
logger.info(`开始采集数据源: ${source.name}`);
// 创建采集器
const collector = CollectorFactory.create(
source.type as CollectorType,
source.config as any,
source.id
);
// 验证配置
if (!collector.validateConfig()) {
throw new Error('Invalid collector config');
}
// 执行采集
const result = await collector.collect();
if (!result.success) {
throw new Error(result.error || 'Collection failed');
}
// 保存资讯(去重)
for (const article of result.articles) {
try {
// 检查是否已存在(通过 URL 或标题去重)
const existing = await prisma.article.findFirst({
where: {
sourceId: source.id,
OR: [
{ url: article.url || undefined },
{ title: article.title },
],
},
});
if (!existing) {
await prisma.article.create({
data: {
sourceId: source.id,
title: article.title,
content: article.content,
url: article.url,
publishedAt: article.publishedAt,
collectedAt: new Date(),
rawData: article.rawData,
},
});
articlesCount++;
}
} catch (error) {
logger.warn('保存资讯失败', { title: article.title, error });
}
}
// 更新数据源的最后采集时间
await prisma.source.update({
where: { id: source.id },
data: { lastCollectedAt: new Date() },
});
logger.info(`数据源 ${source.name} 采集完成,新增 ${articlesCount} 条资讯`);
} catch (error) {
status = 'failed';
errorMessage = error instanceof Error ? error.message : 'Unknown error';
logger.error(`数据源采集失败`, { sourceId, error: errorMessage });
} finally {
// 记录采集日志
await prisma.collectionLog.create({
data: {
sourceId,
status,
errorMessage,
articlesCount,
startedAt: new Date(startTime),
finishedAt: new Date(),
durationMs: Date.now() - startTime,
},
});
}
}
/**
* 采集所有启用的数据源
*/
async collectAllSources(): Promise<void> {
const sources = await prisma.source.findMany({
where: { enabled: true },
});
logger.info(`开始采集 ${sources.length} 个数据源`);
for (const source of sources) {
await this.collectSource(source.id);
}
logger.info('所有数据源采集完成');
}
/**
* 获取采集统计信息
*/
async getCollectionStats() {
const sources = await prisma.source.findMany({
include: {
collectionLogs: {
orderBy: { createdAt: 'desc' },
take: 1,
},
_count: {
select: { articles: true },
},
},
});
return sources.map((source) => ({
id: source.id,
name: source.name,
type: source.type,
enabled: source.enabled,
lastCollectedAt: source.lastCollectedAt,
articleCount: source._count.articles,
lastLog: source.collectionLogs[0] || null,
}));
}
}