757 lines
18 KiB
Markdown
757 lines
18 KiB
Markdown
# 任务 04:采集器实现
|
||||
|
|
|
|||
|
|
## 任务概述
|
|||
|
|
实现插件式采集器架构,支持 API、Playwright 网页爬取、RSS 三种数据源类型。
|
|||
|
|
|
|||
|
|
## 前置条件
|
|||
|
|
- 任务 01、02、03 已完成
|
|||
|
|
- 后端核心框架已搭建
|
|||
|
|
|
|||
|
|
## 任务目标
|
|||
|
|
- 创建采集器基类接口
|
|||
|
|
- 实现 API 采集器
|
|||
|
|
- 实现 Playwright 采集器
|
|||
|
|
- 实现 RSS 采集器
|
|||
|
|
- 创建采集器工厂
|
|||
|
|
- 实现采集服务
|
|||
|
|
|
|||
|
|
## 详细步骤
|
|||
|
|
|
|||
|
|
### 1. 创建采集器类型定义
|
|||
|
|
|
|||
|
|
创建 `backend/src/types/collector.ts`:
|
|||
|
|
|
|||
|
|
```typescript
|
|||
|
|
export type CollectorType = 'api' | 'playwright' | 'rss'
|
|||
|
|
|
|||
|
|
export interface CollectorConfig {
|
|||
|
|
[key: string]: any
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
export interface CollectedArticle {
|
|||
|
|
title: string
|
|||
|
|
content?: string
|
|||
|
|
url?: string
|
|||
|
|
publishedAt?: Date
|
|||
|
|
rawData?: any
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
export interface CollectionResult {
|
|||
|
|
articles: CollectedArticle[]
|
|||
|
|
success: boolean
|
|||
|
|
error?: string
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 2. 创建采集器基类
|
|||
|
|
|
|||
|
|
创建 `backend/src/collectors/base.collector.ts`:
|
|||
|
|
|
|||
|
|
```typescript
|
|||
|
|
import type { CollectorType, CollectorConfig, CollectionResult } from '../types/collector'
|
|||
|
|
|
|||
|
|
export abstract class BaseCollector {
|
|||
|
|
constructor(
|
|||
|
|
protected config: CollectorConfig,
|
|||
|
|
protected sourceId: number
|
|||
|
|
) {}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 执行采集
|
|||
|
|
*/
|
|||
|
|
abstract collect(): Promise<CollectionResult>
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 验证配置
|
|||
|
|
*/
|
|||
|
|
abstract validateConfig(): boolean
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 获取采集器类型
|
|||
|
|
*/
|
|||
|
|
abstract getType(): CollectorType
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 清理资源(可选)
|
|||
|
|
*/
|
|||
|
|
async cleanup(): Promise<void> {
|
|||
|
|
// 默认不需要清理
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 3. 实现 API 采集器
|
|||
|
|
|
|||
|
|
创建 `backend/src/collectors/api.collector.ts`:
|
|||
|
|
|
|||
|
|
```typescript
|
|||
|
|
import { BaseCollector } from './base.collector'
|
|||
|
|
import type { CollectorType, CollectionResult, CollectedArticle } from '../types/collector'
|
|||
|
|
import { logger } from '../utils/logger'
|
|||
|
|
|
|||
|
|
interface ApiCollectorConfig {
|
|||
|
|
url: string
|
|||
|
|
method?: 'GET' | 'POST'
|
|||
|
|
headers?: Record<string, string>
|
|||
|
|
params?: Record<string, any>
|
|||
|
|
body?: any
|
|||
|
|
dataPath?: string // 数据在响应中的路径,如 "data.items"
|
|||
|
|
mapping: {
|
|||
|
|
title: string
|
|||
|
|
content?: string
|
|||
|
|
url?: string
|
|||
|
|
publishedAt?: string
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
export class ApiCollector extends BaseCollector {
|
|||
|
|
private config: ApiCollectorConfig
|
|||
|
|
|
|||
|
|
constructor(config: ApiCollectorConfig, sourceId: number) {
|
|||
|
|
super(config, sourceId)
|
|||
|
|
this.config = config
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
async collect(): Promise<CollectionResult> {
|
|||
|
|
try {
|
|||
|
|
logger.info(`API采集器开始采集: ${this.config.url}`)
|
|||
|
|
|
|||
|
|
// 构建请求
|
|||
|
|
const url = new URL(this.config.url)
|
|||
|
|
if (this.config.params) {
|
|||
|
|
Object.entries(this.config.params).forEach(([key, value]) => {
|
|||
|
|
url.searchParams.append(key, String(value))
|
|||
|
|
})
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
const options: RequestInit = {
|
|||
|
|
method: this.config.method || 'GET',
|
|||
|
|
headers: {
|
|||
|
|
'User-Agent': 'News-Aggregator/1.0',
|
|||
|
|
...this.config.headers,
|
|||
|
|
},
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if (this.config.body && this.config.method === 'POST') {
|
|||
|
|
options.body = JSON.stringify(this.config.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 = data
|
|||
|
|
if (this.config.dataPath) {
|
|||
|
|
items = this.getNestedValue(data, this.config.dataPath)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if (!Array.isArray(items)) {
|
|||
|
|
items = [items]
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 映射数据
|
|||
|
|
const articles: CollectedArticle[] = items.map((item: any) => {
|
|||
|
|
const article: CollectedArticle = {
|
|||
|
|
title: this.getNestedValue(item, this.config.mapping.title),
|
|||
|
|
rawData: item,
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if (this.config.mapping.content) {
|
|||
|
|
article.content = this.getNestedValue(item, this.config.mapping.content)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if (this.config.mapping.url) {
|
|||
|
|
article.url = this.getNestedValue(item, this.config.mapping.url)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if (this.config.mapping.publishedAt) {
|
|||
|
|
const dateValue = this.getNestedValue(item, this.config.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.config.url &&
|
|||
|
|
this.config.mapping &&
|
|||
|
|
this.config.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
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 4. 实现 Playwright 采集器
|
|||
|
|
|
|||
|
|
创建 `backend/src/collectors/playwright.collector.ts`:
|
|||
|
|
|
|||
|
|
```typescript
|
|||
|
|
import { BaseCollector } from './base.collector'
|
|||
|
|
import type { CollectorType, CollectionResult, CollectedArticle } from '../types/collector'
|
|||
|
|
import { chromium, type Browser, type Page } from 'playwright'
|
|||
|
|
import { logger } from '../utils/logger'
|
|||
|
|
|
|||
|
|
interface PlaywrightCollectorConfig {
|
|||
|
|
url: string
|
|||
|
|
selectors: {
|
|||
|
|
items: string // 列表项选择器
|
|||
|
|
title: string // 标题选择器(相对于 item)
|
|||
|
|
content?: string // 内容选择器(相对于 item)
|
|||
|
|
url?: string // 链接选择器(相对于 item)
|
|||
|
|
publishedAt?: string // 日期选择器(相对于 item)
|
|||
|
|
}
|
|||
|
|
waitFor?: string // 等待的选择器
|
|||
|
|
waitTimeout?: number // 等待超时时间(毫秒)
|
|||
|
|
script?: string // 可选的自定义脚本
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
export class PlaywrightCollector extends BaseCollector {
|
|||
|
|
private config: PlaywrightCollectorConfig
|
|||
|
|
private browser?: Browser
|
|||
|
|
|
|||
|
|
constructor(config: PlaywrightCollectorConfig, sourceId: number) {
|
|||
|
|
super(config, sourceId)
|
|||
|
|
this.config = config
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
async collect(): Promise<CollectionResult> {
|
|||
|
|
try {
|
|||
|
|
logger.info(`Playwright采集器开始采集: ${this.config.url}`)
|
|||
|
|
|
|||
|
|
// 启动浏览器
|
|||
|
|
this.browser = await chromium.launch({
|
|||
|
|
headless: true,
|
|||
|
|
})
|
|||
|
|
|
|||
|
|
const page = await this.browser.newPage()
|
|||
|
|
|
|||
|
|
// 设置 User-Agent
|
|||
|
|
await page.setExtraHTTPHeaders({
|
|||
|
|
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
|
|||
|
|
})
|
|||
|
|
|
|||
|
|
// 访问页面
|
|||
|
|
await page.goto(this.config.url, {
|
|||
|
|
waitUntil: 'networkidle',
|
|||
|
|
timeout: 30000,
|
|||
|
|
})
|
|||
|
|
|
|||
|
|
// 等待内容加载
|
|||
|
|
if (this.config.waitFor) {
|
|||
|
|
await page.waitForSelector(this.config.waitFor, {
|
|||
|
|
timeout: this.config.waitTimeout || 10000,
|
|||
|
|
})
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 执行自定义脚本(如果有)
|
|||
|
|
if (this.config.script) {
|
|||
|
|
await page.evaluate(this.config.script)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 提取数据
|
|||
|
|
const articles = await this.extractArticles(page)
|
|||
|
|
|
|||
|
|
logger.info(`Playwright采集器完成,采集到 ${articles.length} 条资讯`)
|
|||
|
|
|
|||
|
|
return {
|
|||
|
|
articles,
|
|||
|
|
success: true,
|
|||
|
|
}
|
|||
|
|
} catch (error) {
|
|||
|
|
logger.error('Playwright采集器失败', error)
|
|||
|
|
return {
|
|||
|
|
articles: [],
|
|||
|
|
success: false,
|
|||
|
|
error: error instanceof Error ? error.message : 'Unknown error',
|
|||
|
|
}
|
|||
|
|
} finally {
|
|||
|
|
await this.cleanup()
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private async extractArticles(page: Page): Promise<CollectedArticle[]> {
|
|||
|
|
const items = await page.$$(this.config.selectors.items)
|
|||
|
|
const articles: CollectedArticle[] = []
|
|||
|
|
|
|||
|
|
for (const item of items) {
|
|||
|
|
try {
|
|||
|
|
const article: CollectedArticle = {
|
|||
|
|
title: '',
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 提取标题
|
|||
|
|
const titleElement = await item.$(this.config.selectors.title)
|
|||
|
|
if (titleElement) {
|
|||
|
|
article.title = (await titleElement.textContent())?.trim() || ''
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 提取内容
|
|||
|
|
if (this.config.selectors.content) {
|
|||
|
|
const contentElement = await item.$(this.config.selectors.content)
|
|||
|
|
if (contentElement) {
|
|||
|
|
article.content = (await contentElement.textContent())?.trim()
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 提取链接
|
|||
|
|
if (this.config.selectors.url) {
|
|||
|
|
const urlElement = await item.$(this.config.selectors.url)
|
|||
|
|
if (urlElement) {
|
|||
|
|
const href = await urlElement.getAttribute('href')
|
|||
|
|
if (href) {
|
|||
|
|
// 处理相对路径
|
|||
|
|
article.url = new URL(href, this.config.url).toString()
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 提取日期
|
|||
|
|
if (this.config.selectors.publishedAt) {
|
|||
|
|
const dateElement = await item.$(this.config.selectors.publishedAt)
|
|||
|
|
if (dateElement) {
|
|||
|
|
const dateText = (await dateElement.textContent())?.trim()
|
|||
|
|
if (dateText) {
|
|||
|
|
article.publishedAt = this.parseDate(dateText)
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if (article.title) {
|
|||
|
|
articles.push(article)
|
|||
|
|
}
|
|||
|
|
} catch (error) {
|
|||
|
|
logger.warn('提取单条资讯失败', error)
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return articles
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
validateConfig(): boolean {
|
|||
|
|
return !!(
|
|||
|
|
this.config.url &&
|
|||
|
|
this.config.selectors &&
|
|||
|
|
this.config.selectors.items &&
|
|||
|
|
this.config.selectors.title
|
|||
|
|
)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
getType(): CollectorType {
|
|||
|
|
return 'playwright'
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
async cleanup(): Promise<void> {
|
|||
|
|
if (this.browser) {
|
|||
|
|
await this.browser.close()
|
|||
|
|
this.browser = undefined
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private parseDate(value: string): Date | undefined {
|
|||
|
|
const date = new Date(value)
|
|||
|
|
return isNaN(date.getTime()) ? undefined : date
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 5. 实现 RSS 采集器
|
|||
|
|
|
|||
|
|
安装 RSS 解析库:
|
|||
|
|
```bash
|
|||
|
|
npm install rss-parser
|
|||
|
|
npm install -D @types/rss-parser
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
创建 `backend/src/collectors/rss.collector.ts`:
|
|||
|
|
|
|||
|
|
```typescript
|
|||
|
|
import { BaseCollector } from './base.collector'
|
|||
|
|
import type { CollectorType, CollectionResult, CollectedArticle } from '../types/collector'
|
|||
|
|
import Parser from 'rss-parser'
|
|||
|
|
import { logger } from '../utils/logger'
|
|||
|
|
|
|||
|
|
interface RssCollectorConfig {
|
|||
|
|
url: string
|
|||
|
|
customFields?: {
|
|||
|
|
item?: string[]
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
export class RssCollector extends BaseCollector {
|
|||
|
|
private config: RssCollectorConfig
|
|||
|
|
private parser: Parser
|
|||
|
|
|
|||
|
|
constructor(config: RssCollectorConfig, sourceId: number) {
|
|||
|
|
super(config, sourceId)
|
|||
|
|
this.config = config
|
|||
|
|
this.parser = new Parser({
|
|||
|
|
customFields: this.config.customFields,
|
|||
|
|
})
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
async collect(): Promise<CollectionResult> {
|
|||
|
|
try {
|
|||
|
|
logger.info(`RSS采集器开始采集: ${this.config.url}`)
|
|||
|
|
|
|||
|
|
const feed = await this.parser.parseURL(this.config.url)
|
|||
|
|
|
|||
|
|
const articles: CollectedArticle[] = feed.items.map((item) => {
|
|||
|
|
const article: CollectedArticle = {
|
|||
|
|
title: item.title || '',
|
|||
|
|
content: item.contentSnippet || item.content,
|
|||
|
|
url: item.link,
|
|||
|
|
rawData: item,
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if (item.pubDate) {
|
|||
|
|
article.publishedAt = new Date(item.pubDate)
|
|||
|
|
} else if (item.isoDate) {
|
|||
|
|
article.publishedAt = new Date(item.isoDate)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return article
|
|||
|
|
})
|
|||
|
|
|
|||
|
|
logger.info(`RSS采集器完成,采集到 ${articles.length} 条资讯`)
|
|||
|
|
|
|||
|
|
return {
|
|||
|
|
articles,
|
|||
|
|
success: true,
|
|||
|
|
}
|
|||
|
|
} catch (error) {
|
|||
|
|
logger.error('RSS采集器失败', error)
|
|||
|
|
return {
|
|||
|
|
articles: [],
|
|||
|
|
success: false,
|
|||
|
|
error: error instanceof Error ? error.message : 'Unknown error',
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
validateConfig(): boolean {
|
|||
|
|
return !!this.config.url
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
getType(): CollectorType {
|
|||
|
|
return 'rss'
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 6. 创建采集器工厂
|
|||
|
|
|
|||
|
|
创建 `backend/src/collectors/collector.factory.ts`:
|
|||
|
|
|
|||
|
|
```typescript
|
|||
|
|
import type { BaseCollector } from './base.collector'
|
|||
|
|
import { ApiCollector } from './api.collector'
|
|||
|
|
import { PlaywrightCollector } from './playwright.collector'
|
|||
|
|
import { RssCollector } from './rss.collector'
|
|||
|
|
import type { CollectorType, CollectorConfig } from '../types/collector'
|
|||
|
|
|
|||
|
|
export class CollectorFactory {
|
|||
|
|
static create(
|
|||
|
|
type: CollectorType,
|
|||
|
|
config: CollectorConfig,
|
|||
|
|
sourceId: number
|
|||
|
|
): BaseCollector {
|
|||
|
|
switch (type) {
|
|||
|
|
case 'api':
|
|||
|
|
return new ApiCollector(config, sourceId)
|
|||
|
|
case 'playwright':
|
|||
|
|
return new PlaywrightCollector(config, sourceId)
|
|||
|
|
case 'rss':
|
|||
|
|
return new RssCollector(config, sourceId)
|
|||
|
|
default:
|
|||
|
|
throw new Error(`Unknown collector type: ${type}`)
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 7. 创建采集服务
|
|||
|
|
|
|||
|
|
创建 `backend/src/services/collector.service.ts`:
|
|||
|
|
|
|||
|
|
```typescript
|
|||
|
|
import prisma from '../utils/prisma'
|
|||
|
|
import { CollectorFactory } from '../collectors/collector.factory'
|
|||
|
|
import { logger } from '../utils/logger'
|
|||
|
|
import type { Source } from '@prisma/client'
|
|||
|
|
|
|||
|
|
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 any,
|
|||
|
|
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 {
|
|||
|
|
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('所有数据源采集完成')
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 8. 创建采集器导出
|
|||
|
|
|
|||
|
|
创建 `backend/src/collectors/index.ts`:
|
|||
|
|
|
|||
|
|
```typescript
|
|||
|
|
export * from './base.collector'
|
|||
|
|
export * from './api.collector'
|
|||
|
|
export * from './playwright.collector'
|
|||
|
|
export * from './rss.collector'
|
|||
|
|
export * from './collector.factory'
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
创建 `backend/src/services/index.ts`:
|
|||
|
|
|
|||
|
|
```typescript
|
|||
|
|
export * from './collector.service'
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
## 验证步骤
|
|||
|
|
|
|||
|
|
### 1. 创建测试脚本
|
|||
|
|
|
|||
|
|
创建 `backend/src/test-collector.ts`:
|
|||
|
|
|
|||
|
|
```typescript
|
|||
|
|
import { CollectorService } from './services/collector.service'
|
|||
|
|
import prisma from './utils/prisma'
|
|||
|
|
|
|||
|
|
async function test() {
|
|||
|
|
const collectorService = new CollectorService()
|
|||
|
|
|
|||
|
|
// 测试采集单个数据源
|
|||
|
|
const sources = await prisma.source.findMany({
|
|||
|
|
where: { enabled: true },
|
|||
|
|
take: 1,
|
|||
|
|
})
|
|||
|
|
|
|||
|
|
if (sources.length > 0) {
|
|||
|
|
console.log(`测试采集数据源: ${sources[0].name}`)
|
|||
|
|
await collectorService.collectSource(sources[0].id)
|
|||
|
|
|
|||
|
|
// 查看采集结果
|
|||
|
|
const articles = await prisma.article.findMany({
|
|||
|
|
where: { sourceId: sources[0].id },
|
|||
|
|
take: 5,
|
|||
|
|
orderBy: { collectedAt: 'desc' },
|
|||
|
|
})
|
|||
|
|
|
|||
|
|
console.log(`采集到 ${articles.length} 条资讯:`)
|
|||
|
|
articles.forEach((article) => {
|
|||
|
|
console.log(`- ${article.title}`)
|
|||
|
|
})
|
|||
|
|
|
|||
|
|
// 查看采集日志
|
|||
|
|
const logs = await prisma.collectionLog.findMany({
|
|||
|
|
where: { sourceId: sources[0].id },
|
|||
|
|
take: 1,
|
|||
|
|
orderBy: { createdAt: 'desc' },
|
|||
|
|
})
|
|||
|
|
|
|||
|
|
console.log('最近的采集日志:', logs[0])
|
|||
|
|
} else {
|
|||
|
|
console.log('没有启用的数据源')
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
test()
|
|||
|
|
.catch(console.error)
|
|||
|
|
.finally(() => prisma.$disconnect())
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 2. 运行测试
|
|||
|
|
|
|||
|
|
```bash
|
|||
|
|
npx tsx src/test-collector.ts
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 3. 验证数据库
|
|||
|
|
|
|||
|
|
使用 Prisma Studio 查看:
|
|||
|
|
```bash
|
|||
|
|
npm run prisma:studio
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
检查:
|
|||
|
|
- articles 表有新数据
|
|||
|
|
- collection_logs 表有采集记录
|
|||
|
|
|
|||
|
|
## 预期产物
|
|||
|
|
|
|||
|
|
- ✅ 采集器基类创建完成
|
|||
|
|
- ✅ API 采集器实现完成
|
|||
|
|
- ✅ Playwright 采集器实现完成
|
|||
|
|
- ✅ RSS 采集器实现完成
|
|||
|
|
- ✅ 采集器工厂创建完成
|
|||
|
|
- ✅ 采集服务实现完成
|
|||
|
|
- ✅ 采集功能测试通过
|
|||
|
|
|
|||
|
|
## 下一步
|
|||
|
|
|
|||
|
|
完成本任务后,继续 [任务 05:内容处理](./05-processor.md)。
|