Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
697430feed | ||
|
|
6df528f187 | ||
|
|
51eb7d4292 | ||
|
|
881bbb64a3 | ||
|
|
5746676819 | ||
|
|
75c765af93 | ||
|
|
bb9d691f7a | ||
|
|
d8553c06fa | ||
|
|
fe7714a3a6 | ||
|
|
b8791ee556 |
No files matched your search
Generated
+1679
-1
File diff suppressed because it is too large.
Load diff
+10
-1
@@ -7,6 +7,9 @@
|
||||
"dev": "tsx watch src/app.ts",
|
||||
"build": "tsc",
|
||||
"start": "node dist/app.js",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"test:coverage": "vitest run --coverage",
|
||||
"prisma:generate": "prisma generate",
|
||||
"prisma:migrate": "prisma migrate dev",
|
||||
"prisma:studio": "prisma studio"
|
||||
@@ -22,16 +25,22 @@
|
||||
"dotenv": "^17.2.3",
|
||||
"fastify": "^5.7.4",
|
||||
"node-cron": "^4.2.1",
|
||||
"nodemailer": "^8.0.0",
|
||||
"openai": "^6.17.0",
|
||||
"playwright": "^1.58.1",
|
||||
"prisma": "^5.22.0",
|
||||
"rss-parser": "^3.13.0",
|
||||
"winston": "^3.19.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^25.2.0",
|
||||
"@types/node-cron": "^3.0.11",
|
||||
"@types/nodemailer": "^7.0.9",
|
||||
"@types/supertest": "^6.0.3",
|
||||
"nodemon": "^3.1.11",
|
||||
"supertest": "^7.2.2",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "^5.9.3"
|
||||
"typescript": "^5.9.3",
|
||||
"vitest": "^4.0.18"
|
||||
}
|
||||
}
|
||||
+51
-25
@@ -1,7 +1,21 @@
|
||||
import Fastify from 'fastify';
|
||||
import cors from '@fastify/cors';
|
||||
import { config, validateConfig } from './config';
|
||||
import { connectDatabase, disconnectDatabase } from './config/database';
|
||||
import logger from './utils/logger';
|
||||
import { errorHandler } from './web/middleware/error-handler';
|
||||
import { requestLogger } from './web/middleware/request-logger';
|
||||
import { healthRoutes } from './web/routes/health';
|
||||
import { llmConfigRoutes } from './web/routes/llm-configs';
|
||||
import { sourceRoutes } from './web/routes/sources';
|
||||
import { channelRoutes } from './web/routes/channels';
|
||||
import { topicRoutes } from './web/routes/topics';
|
||||
import { reportRoutes } from './web/routes/reports';
|
||||
import { articleRoutes } from './web/routes/articles';
|
||||
import { collectionLogRoutes } from './web/routes/collection-logs';
|
||||
import { SchedulerService } from './services/scheduler.service';
|
||||
|
||||
let schedulerService: SchedulerService | null = null;
|
||||
|
||||
// 验证配置
|
||||
try {
|
||||
@@ -27,51 +41,55 @@ async function registerPlugins(): Promise<void> {
|
||||
logger.info('CORS 插件已注册');
|
||||
}
|
||||
|
||||
// 注册中间件
|
||||
async function registerMiddleware(): Promise<void> {
|
||||
// 请求日志
|
||||
app.addHook('onRequest', requestLogger);
|
||||
logger.info('中间件已注册');
|
||||
}
|
||||
|
||||
// 注册路由
|
||||
async function registerRoutes(): Promise<void> {
|
||||
// 健康检查
|
||||
app.get('/api/v1/health', async () => {
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
status: 'ok',
|
||||
timestamp: new Date().toISOString(),
|
||||
version: '1.0.0',
|
||||
},
|
||||
};
|
||||
});
|
||||
// 健康检查路由
|
||||
await app.register(healthRoutes, { prefix: '/api/v1' });
|
||||
|
||||
// API 路由
|
||||
await app.register(llmConfigRoutes, { prefix: '/api/v1/llm-configs' });
|
||||
await app.register(sourceRoutes, { prefix: '/api/v1/sources' });
|
||||
await app.register(channelRoutes, { prefix: '/api/v1/channels' });
|
||||
await app.register(topicRoutes, { prefix: '/api/v1/topics' });
|
||||
await app.register(reportRoutes, { prefix: '/api/v1/reports' });
|
||||
await app.register(articleRoutes, { prefix: '/api/v1/articles' });
|
||||
await app.register(collectionLogRoutes, { prefix: '/api/v1/collection-logs' });
|
||||
|
||||
logger.info('路由已注册');
|
||||
}
|
||||
|
||||
// 错误处理
|
||||
app.setErrorHandler((error, request, reply) => {
|
||||
logger.error('请求处理错误:', {
|
||||
error: error.message,
|
||||
stack: error.stack,
|
||||
url: request.url,
|
||||
method: request.method,
|
||||
});
|
||||
|
||||
reply.status(error.statusCode || 500).send({
|
||||
success: false,
|
||||
error: error.message || '服务器内部错误',
|
||||
});
|
||||
});
|
||||
app.setErrorHandler(errorHandler);
|
||||
|
||||
// 启动服务器
|
||||
async function start(): Promise<void> {
|
||||
try {
|
||||
// 连接数据库
|
||||
await connectDatabase();
|
||||
|
||||
// 注册插件和中间件
|
||||
await registerPlugins();
|
||||
await registerMiddleware();
|
||||
await registerRoutes();
|
||||
|
||||
// 启动调度器
|
||||
schedulerService = new SchedulerService();
|
||||
await schedulerService.start();
|
||||
|
||||
await app.listen({
|
||||
port: config.port,
|
||||
host: '0.0.0.0',
|
||||
});
|
||||
|
||||
logger.info(`🚀 服务器启动成功,监听端口 ${config.port}`);
|
||||
logger.info(`📚 API 文档: http://localhost:${config.port}/api/v1/health`);
|
||||
logger.info(`📚 健康检查: http://localhost:${config.port}/api/v1/health`);
|
||||
} catch (error) {
|
||||
logger.error('服务器启动失败:', error);
|
||||
process.exit(1);
|
||||
@@ -92,13 +110,21 @@ process.on('unhandledRejection', (reason, promise) => {
|
||||
// 优雅关闭
|
||||
process.on('SIGTERM', async () => {
|
||||
logger.info('SIGTERM 信号收到,正在关闭服务器...');
|
||||
if (schedulerService) {
|
||||
schedulerService.stop();
|
||||
}
|
||||
await app.close();
|
||||
await disconnectDatabase();
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
process.on('SIGINT', async () => {
|
||||
logger.info('SIGINT 信号收到,正在关闭服务器...');
|
||||
if (schedulerService) {
|
||||
schedulerService.stop();
|
||||
}
|
||||
await app.close();
|
||||
await disconnectDatabase();
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
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 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import {
|
||||
CollectorType,
|
||||
CollectorConfig,
|
||||
CollectionResult,
|
||||
CollectedArticle,
|
||||
} from '../types/collector';
|
||||
|
||||
export abstract class BaseCollector {
|
||||
protected sourceId: number;
|
||||
protected config: CollectorConfig;
|
||||
|
||||
constructor(config: CollectorConfig, sourceId: number) {
|
||||
this.config = config;
|
||||
this.sourceId = sourceId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行采集
|
||||
*/
|
||||
abstract collect(): Promise<CollectionResult>;
|
||||
|
||||
/**
|
||||
* 验证配置
|
||||
*/
|
||||
abstract validateConfig(): boolean;
|
||||
|
||||
/**
|
||||
* 获取采集器类型
|
||||
*/
|
||||
abstract getType(): CollectorType;
|
||||
|
||||
/**
|
||||
* 清理资源(可选)
|
||||
*/
|
||||
async cleanup(): Promise<void> {
|
||||
// 默认不需要清理
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { BaseCollector } from './base.collector';
|
||||
import { ApiCollector } from './api.collector';
|
||||
import { PlaywrightCollector } from './playwright.collector';
|
||||
import { RssCollector } from './rss.collector';
|
||||
import { 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 as any, sourceId);
|
||||
case 'playwright':
|
||||
return new PlaywrightCollector(config as any, sourceId);
|
||||
case 'rss':
|
||||
return new RssCollector(config as any, sourceId);
|
||||
default:
|
||||
throw new Error(`Unknown collector type: ${type}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
export * from './base.collector';
|
||||
export * from './api.collector';
|
||||
export * from './playwright.collector';
|
||||
export * from './rss.collector';
|
||||
export * from './collector.factory';
|
||||
@@ -0,0 +1,156 @@
|
||||
import { BaseCollector } from './base.collector';
|
||||
import {
|
||||
CollectorType,
|
||||
CollectionResult,
|
||||
CollectedArticle,
|
||||
PlaywrightCollectorConfig,
|
||||
} from '../types/collector';
|
||||
import { chromium, Browser, Page } from 'playwright';
|
||||
import logger from '../utils/logger';
|
||||
|
||||
export class PlaywrightCollector extends BaseCollector {
|
||||
private playwrightConfig: PlaywrightCollectorConfig;
|
||||
private browser?: Browser;
|
||||
|
||||
constructor(config: PlaywrightCollectorConfig, sourceId: number) {
|
||||
super(config, sourceId);
|
||||
this.playwrightConfig = config;
|
||||
}
|
||||
|
||||
async collect(): Promise<CollectionResult> {
|
||||
try {
|
||||
logger.info(`Playwright采集器开始采集: ${this.playwrightConfig.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.playwrightConfig.url, {
|
||||
waitUntil: 'networkidle',
|
||||
timeout: 30000,
|
||||
});
|
||||
|
||||
// 等待内容加载
|
||||
if (this.playwrightConfig.waitFor) {
|
||||
await page.waitForSelector(this.playwrightConfig.waitFor, {
|
||||
timeout: this.playwrightConfig.waitTimeout || 10000,
|
||||
});
|
||||
}
|
||||
|
||||
// 执行自定义脚本(如果有)
|
||||
if (this.playwrightConfig.script) {
|
||||
await page.evaluate(this.playwrightConfig.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.playwrightConfig.selectors.items);
|
||||
const articles: CollectedArticle[] = [];
|
||||
|
||||
for (const item of items) {
|
||||
try {
|
||||
const article: CollectedArticle = {
|
||||
title: '',
|
||||
};
|
||||
|
||||
// 提取标题
|
||||
const titleElement = await item.$(this.playwrightConfig.selectors.title);
|
||||
if (titleElement) {
|
||||
article.title = (await titleElement.textContent())?.trim() || '';
|
||||
}
|
||||
|
||||
// 提取内容
|
||||
if (this.playwrightConfig.selectors.content) {
|
||||
const contentElement = await item.$(this.playwrightConfig.selectors.content);
|
||||
if (contentElement) {
|
||||
article.content = (await contentElement.textContent())?.trim();
|
||||
}
|
||||
}
|
||||
|
||||
// 提取链接
|
||||
if (this.playwrightConfig.selectors.url) {
|
||||
const urlElement = await item.$(this.playwrightConfig.selectors.url);
|
||||
if (urlElement) {
|
||||
const href = await urlElement.getAttribute('href');
|
||||
if (href) {
|
||||
article.url = new URL(href, this.playwrightConfig.url).toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 提取日期
|
||||
if (this.playwrightConfig.selectors.publishedAt) {
|
||||
const dateElement = await item.$(this.playwrightConfig.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.playwrightConfig.url &&
|
||||
this.playwrightConfig.selectors &&
|
||||
this.playwrightConfig.selectors.items &&
|
||||
this.playwrightConfig.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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { BaseCollector } from './base.collector';
|
||||
import {
|
||||
CollectorType,
|
||||
CollectionResult,
|
||||
CollectedArticle,
|
||||
RssCollectorConfig,
|
||||
} from '../types/collector';
|
||||
import Parser from 'rss-parser';
|
||||
import logger from '../utils/logger';
|
||||
|
||||
export class RssCollector extends BaseCollector {
|
||||
private rssConfig: RssCollectorConfig;
|
||||
private parser: Parser;
|
||||
|
||||
constructor(config: RssCollectorConfig, sourceId: number) {
|
||||
super(config, sourceId);
|
||||
this.rssConfig = config;
|
||||
this.parser = new Parser({
|
||||
customFields: this.rssConfig.customFields,
|
||||
});
|
||||
}
|
||||
|
||||
async collect(): Promise<CollectionResult> {
|
||||
try {
|
||||
logger.info(`RSS采集器开始采集: ${this.rssConfig.url}`);
|
||||
|
||||
const feed = await this.parser.parseURL(this.rssConfig.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.rssConfig.url;
|
||||
}
|
||||
|
||||
getType(): CollectorType {
|
||||
return 'rss';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { DistributorType, DistributorConfig, DistributionResult, ReportSummary } from '../types/distributor';
|
||||
|
||||
export abstract class BaseDistributor {
|
||||
protected channelId: number;
|
||||
protected config: DistributorConfig;
|
||||
|
||||
constructor(config: DistributorConfig, channelId: number) {
|
||||
this.config = config;
|
||||
this.channelId = channelId;
|
||||
}
|
||||
|
||||
abstract distribute(summary: ReportSummary, fullContent: string): Promise<DistributionResult>;
|
||||
abstract validateConfig(): boolean;
|
||||
abstract getType(): DistributorType;
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import { BaseDistributor } from './base.distributor';
|
||||
import { DistributorType, DistributionResult, ReportSummary, DingtalkDistributorConfig } from '../types/distributor';
|
||||
import crypto from 'crypto';
|
||||
import logger from '../utils/logger';
|
||||
|
||||
export class DingtalkDistributor extends BaseDistributor {
|
||||
private dingtalkConfig: DingtalkDistributorConfig;
|
||||
|
||||
constructor(config: DingtalkDistributorConfig, channelId: number) {
|
||||
super(config, channelId);
|
||||
this.dingtalkConfig = config;
|
||||
}
|
||||
|
||||
async distribute(summary: ReportSummary, fullContent: string): Promise<DistributionResult> {
|
||||
try {
|
||||
logger.info('钉钉分发器开始发送', { title: summary.title });
|
||||
|
||||
let url = this.dingtalkConfig.webhook;
|
||||
if (this.dingtalkConfig.secret) {
|
||||
const timestamp = Date.now();
|
||||
const sign = this.generateSign(timestamp, this.dingtalkConfig.secret);
|
||||
url = `${url}×tamp=${timestamp}&sign=${sign}`;
|
||||
}
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(this.buildMessage(summary)),
|
||||
});
|
||||
|
||||
const result = (await response.json()) as { errcode: number; errmsg: string };
|
||||
|
||||
if (result.errcode !== 0) {
|
||||
throw new Error(`钉钉 API 错误: ${result.errmsg}`);
|
||||
}
|
||||
|
||||
logger.info('钉钉消息发送成功');
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
logger.error('钉钉消息发送失败', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Unknown error',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
validateConfig(): boolean {
|
||||
return !!this.dingtalkConfig.webhook;
|
||||
}
|
||||
|
||||
getType(): DistributorType {
|
||||
return 'dingtalk';
|
||||
}
|
||||
|
||||
private generateSign(timestamp: number, secret: string): string {
|
||||
const stringToSign = `${timestamp}\n${secret}`;
|
||||
const hmac = crypto.createHmac('sha256', secret);
|
||||
hmac.update(stringToSign);
|
||||
return encodeURIComponent(hmac.digest('base64'));
|
||||
}
|
||||
|
||||
private buildMessage(summary: ReportSummary) {
|
||||
return {
|
||||
msgtype: 'markdown',
|
||||
markdown: {
|
||||
title: summary.title,
|
||||
text: `# ${summary.title}
|
||||
|
||||
**主题**: ${summary.topicName}
|
||||
**资讯数量**: ${summary.articleCount} 条
|
||||
**时间范围**: ${this.formatDate(summary.periodStart)} - ${this.formatDate(summary.periodEnd)}
|
||||
|
||||
[查看完整报告](${summary.webUrl})`,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private formatDate(date: Date): string {
|
||||
return date.toLocaleDateString('zh-CN');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { BaseDistributor } from './base.distributor';
|
||||
import { EmailDistributor } from './email.distributor';
|
||||
import { DingtalkDistributor } from './dingtalk.distributor';
|
||||
import { WechatDistributor } from './wechat.distributor';
|
||||
import { SlackDistributor } from './slack.distributor';
|
||||
import { DistributorType, DistributorConfig } from '../types/distributor';
|
||||
|
||||
export class DistributorFactory {
|
||||
static create(
|
||||
type: DistributorType,
|
||||
config: DistributorConfig,
|
||||
channelId: number
|
||||
): BaseDistributor {
|
||||
switch (type) {
|
||||
case 'email':
|
||||
return new EmailDistributor(config as any, channelId);
|
||||
case 'dingtalk':
|
||||
return new DingtalkDistributor(config as any, channelId);
|
||||
case 'wechat':
|
||||
return new WechatDistributor(config as any, channelId);
|
||||
case 'slack':
|
||||
return new SlackDistributor(config as any, channelId);
|
||||
default:
|
||||
throw new Error(`Unknown distributor type: ${type}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import { BaseDistributor } from './base.distributor';
|
||||
import { DistributorType, DistributionResult, ReportSummary, EmailDistributorConfig } from '../types/distributor';
|
||||
import nodemailer from 'nodemailer';
|
||||
import logger from '../utils/logger';
|
||||
|
||||
export class EmailDistributor extends BaseDistributor {
|
||||
private emailConfig: EmailDistributorConfig;
|
||||
|
||||
constructor(config: EmailDistributorConfig, channelId: number) {
|
||||
super(config, channelId);
|
||||
this.emailConfig = config;
|
||||
}
|
||||
|
||||
async distribute(summary: ReportSummary, fullContent: string): Promise<DistributionResult> {
|
||||
try {
|
||||
logger.info('邮件分发器开始发送', { to: this.emailConfig.to, title: summary.title });
|
||||
|
||||
const transporter = nodemailer.createTransport(this.emailConfig.smtp);
|
||||
|
||||
await transporter.sendMail({
|
||||
from: this.emailConfig.from,
|
||||
to: this.emailConfig.to.join(', '),
|
||||
subject: summary.title,
|
||||
text: this.buildTextContent(summary),
|
||||
html: this.buildHtmlContent(summary, fullContent),
|
||||
});
|
||||
|
||||
logger.info('邮件发送成功');
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
logger.error('邮件发送失败', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Unknown error',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
validateConfig(): boolean {
|
||||
return !!(
|
||||
this.emailConfig.smtp?.host &&
|
||||
this.emailConfig.smtp?.auth &&
|
||||
this.emailConfig.from &&
|
||||
this.emailConfig.to?.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
getType(): DistributorType {
|
||||
return 'email';
|
||||
}
|
||||
|
||||
private buildHtmlContent(summary: ReportSummary, fullContent: string): string {
|
||||
const htmlContent = fullContent
|
||||
.replace(/^# (.+)$/gm, '<h1>$1</h1>')
|
||||
.replace(/^## (.+)$/gm, '<h2>$1</h2>')
|
||||
.replace(/^### (.+)$/gm, '<h3>$1</h3>')
|
||||
.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
|
||||
.replace(/\[(.+?)\]\((.+?)\)/g, '<a href="$2">$1</a>')
|
||||
.replace(/\n/g, '<br>');
|
||||
|
||||
return `<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<style>
|
||||
body { font-family: sans-serif; line-height: 1.6; color: #333; max-width: 800px; margin: 0 auto; padding: 20px; }
|
||||
h1 { color: #2c3e50; border-bottom: 2px solid #3498db; padding-bottom: 10px; }
|
||||
a { color: #3498db; }
|
||||
.summary { background: #ecf0f1; padding: 15px; border-radius: 5px; margin: 20px 0; }
|
||||
.button { display: inline-block; padding: 10px 20px; background: #3498db; color: white; text-decoration: none; border-radius: 5px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="summary">
|
||||
<p><strong>主题:</strong> ${summary.topicName}</p>
|
||||
<p><strong>资讯数量:</strong> ${summary.articleCount} 条</p>
|
||||
<p><strong>时间范围:</strong> ${this.formatDate(summary.periodStart)} - ${this.formatDate(summary.periodEnd)}</p>
|
||||
</div>
|
||||
<a href="${summary.webUrl}" class="button">查看完整报告</a>
|
||||
<hr>
|
||||
<div>${htmlContent}</div>
|
||||
<p style="color: #7f8c8d; font-size: 12px; margin-top: 40px;">本邮件由 News Aggregator 自动发送</p>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
private buildTextContent(summary: ReportSummary): string {
|
||||
return `${summary.title}
|
||||
|
||||
主题: ${summary.topicName}
|
||||
资讯数量: ${summary.articleCount} 条
|
||||
时间范围: ${this.formatDate(summary.periodStart)} - ${this.formatDate(summary.periodEnd)}
|
||||
|
||||
查看完整报告: ${summary.webUrl}`;
|
||||
}
|
||||
|
||||
private formatDate(date: Date): string {
|
||||
return date.toLocaleDateString('zh-CN');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
export * from './base.distributor';
|
||||
export * from './email.distributor';
|
||||
export * from './dingtalk.distributor';
|
||||
export * from './wechat.distributor';
|
||||
export * from './slack.distributor';
|
||||
export * from './distributor.factory';
|
||||
@@ -0,0 +1,78 @@
|
||||
import { BaseDistributor } from './base.distributor';
|
||||
import { DistributorType, DistributionResult, ReportSummary, SlackDistributorConfig } from '../types/distributor';
|
||||
import logger from '../utils/logger';
|
||||
|
||||
export class SlackDistributor extends BaseDistributor {
|
||||
private slackConfig: SlackDistributorConfig;
|
||||
|
||||
constructor(config: SlackDistributorConfig, channelId: number) {
|
||||
super(config, channelId);
|
||||
this.slackConfig = config;
|
||||
}
|
||||
|
||||
async distribute(summary: ReportSummary, fullContent: string): Promise<DistributionResult> {
|
||||
try {
|
||||
logger.info('Slack 分发器开始发送', { title: summary.title });
|
||||
|
||||
const response = await fetch(this.slackConfig.webhook, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(this.buildMessage(summary)),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Slack API 错误: ${response.statusText}`);
|
||||
}
|
||||
|
||||
logger.info('Slack 消息发送成功');
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
logger.error('Slack 消息发送失败', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Unknown error',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
validateConfig(): boolean {
|
||||
return !!this.slackConfig.webhook;
|
||||
}
|
||||
|
||||
getType(): DistributorType {
|
||||
return 'slack';
|
||||
}
|
||||
|
||||
private buildMessage(summary: ReportSummary) {
|
||||
return {
|
||||
blocks: [
|
||||
{
|
||||
type: 'header',
|
||||
text: { type: 'plain_text', text: summary.title },
|
||||
},
|
||||
{
|
||||
type: 'section',
|
||||
fields: [
|
||||
{ type: 'mrkdwn', text: `*主题:*\n${summary.topicName}` },
|
||||
{ type: 'mrkdwn', text: `*资讯数量:*\n${summary.articleCount} 条` },
|
||||
{ type: 'mrkdwn', text: `*时间范围:*\n${this.formatDate(summary.periodStart)} - ${this.formatDate(summary.periodEnd)}` },
|
||||
],
|
||||
},
|
||||
{
|
||||
type: 'actions',
|
||||
elements: [
|
||||
{
|
||||
type: 'button',
|
||||
text: { type: 'plain_text', text: '查看完整报告' },
|
||||
url: summary.webUrl,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
private formatDate(date: Date): string {
|
||||
return date.toLocaleDateString('zh-CN');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { BaseDistributor } from './base.distributor';
|
||||
import { DistributorType, DistributionResult, ReportSummary, WechatDistributorConfig } from '../types/distributor';
|
||||
import logger from '../utils/logger';
|
||||
|
||||
export class WechatDistributor extends BaseDistributor {
|
||||
private wechatConfig: WechatDistributorConfig;
|
||||
|
||||
constructor(config: WechatDistributorConfig, channelId: number) {
|
||||
super(config, channelId);
|
||||
this.wechatConfig = config;
|
||||
}
|
||||
|
||||
async distribute(summary: ReportSummary, fullContent: string): Promise<DistributionResult> {
|
||||
try {
|
||||
logger.info('企业微信分发器开始发送', { title: summary.title });
|
||||
|
||||
const response = await fetch(this.wechatConfig.webhook, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(this.buildMessage(summary)),
|
||||
});
|
||||
|
||||
const result = (await response.json()) as { errcode: number; errmsg: string };
|
||||
|
||||
if (result.errcode !== 0) {
|
||||
throw new Error(`企业微信 API 错误: ${result.errmsg}`);
|
||||
}
|
||||
|
||||
logger.info('企业微信消息发送成功');
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
logger.error('企业微信消息发送失败', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Unknown error',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
validateConfig(): boolean {
|
||||
return !!this.wechatConfig.webhook;
|
||||
}
|
||||
|
||||
getType(): DistributorType {
|
||||
return 'wechat';
|
||||
}
|
||||
|
||||
private buildMessage(summary: ReportSummary) {
|
||||
return {
|
||||
msgtype: 'markdown',
|
||||
markdown: {
|
||||
content: `# ${summary.title}
|
||||
|
||||
> 主题: ${summary.topicName}
|
||||
> 资讯数量: ${summary.articleCount} 条
|
||||
> 时间范围: ${this.formatDate(summary.periodStart)} - ${this.formatDate(summary.periodEnd)}
|
||||
|
||||
[查看完整报告](${summary.webUrl})`,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private formatDate(date: Date): string {
|
||||
return date.toLocaleDateString('zh-CN');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
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');
|
||||
}
|
||||
|
||||
// 保存资讯(批量去重)
|
||||
const articlesToCreate = [];
|
||||
for (const article of result.articles) {
|
||||
// 检查是否已存在(通过 URL 或标题去重)
|
||||
const whereConditions: any[] = [{ title: article.title }];
|
||||
if (article.url) {
|
||||
whereConditions.push({ url: article.url });
|
||||
}
|
||||
|
||||
const existing = await prisma.article.findFirst({
|
||||
where: {
|
||||
sourceId: source.id,
|
||||
OR: whereConditions,
|
||||
},
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
articlesToCreate.push({
|
||||
sourceId: source.id,
|
||||
title: article.title,
|
||||
content: article.content,
|
||||
url: article.url,
|
||||
publishedAt: article.publishedAt,
|
||||
collectedAt: new Date(),
|
||||
rawData: article.rawData,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 批量插入
|
||||
if (articlesToCreate.length > 0) {
|
||||
await prisma.article.createMany({
|
||||
data: articlesToCreate,
|
||||
skipDuplicates: true,
|
||||
});
|
||||
articlesCount = articlesToCreate.length;
|
||||
}
|
||||
|
||||
// 更新数据源的最后采集时间
|
||||
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,
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import prisma from '../config/database';
|
||||
import { DistributorFactory } from '../distributors/distributor.factory';
|
||||
import { DistributorType, ReportSummary } from '../types/distributor';
|
||||
import { config } from '../config';
|
||||
import logger from '../utils/logger';
|
||||
|
||||
export class DistributorService {
|
||||
/**
|
||||
* 分发报告到指定渠道
|
||||
*/
|
||||
async distributeReport(reportId: number, channelId: number): Promise<void> {
|
||||
let status: 'success' | 'failed' = 'success';
|
||||
let errorMessage: string | undefined;
|
||||
|
||||
try {
|
||||
const report = await prisma.report.findUnique({
|
||||
where: { id: reportId },
|
||||
include: { topic: true },
|
||||
});
|
||||
|
||||
if (!report) {
|
||||
throw new Error(`Report ${reportId} not found`);
|
||||
}
|
||||
|
||||
const channel = await prisma.channel.findUnique({
|
||||
where: { id: channelId },
|
||||
});
|
||||
|
||||
if (!channel) {
|
||||
throw new Error(`Channel ${channelId} not found`);
|
||||
}
|
||||
|
||||
if (!channel.enabled) {
|
||||
logger.info(`渠道 ${channel.name} 已禁用,跳过分发`);
|
||||
return;
|
||||
}
|
||||
|
||||
logger.info(`开始分发报告: ${report.title} -> ${channel.name}`);
|
||||
|
||||
const distributor = DistributorFactory.create(
|
||||
channel.type as DistributorType,
|
||||
channel.config as any,
|
||||
channel.id
|
||||
);
|
||||
|
||||
if (!distributor.validateConfig()) {
|
||||
throw new Error('Invalid distributor config');
|
||||
}
|
||||
|
||||
const summary: ReportSummary = {
|
||||
title: report.title,
|
||||
topicName: report.topic.name,
|
||||
articleCount: report.articleCount,
|
||||
periodStart: report.periodStart,
|
||||
periodEnd: report.periodEnd,
|
||||
webUrl: this.buildReportUrl(reportId),
|
||||
};
|
||||
|
||||
const result = await distributor.distribute(summary, report.content);
|
||||
|
||||
if (!result.success) {
|
||||
throw new Error(result.error || 'Distribution failed');
|
||||
}
|
||||
|
||||
logger.info(`报告分发成功: ${channel.name}`);
|
||||
} catch (error) {
|
||||
status = 'failed';
|
||||
errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
||||
logger.error('报告分发失败', { reportId, channelId, error: errorMessage });
|
||||
} finally {
|
||||
await prisma.pushLog.create({
|
||||
data: { reportId, channelId, status, errorMessage },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 分发报告到所有关联的渠道
|
||||
*/
|
||||
async distributeReportToAllChannels(reportId: number): Promise<void> {
|
||||
const report = await prisma.report.findUnique({
|
||||
where: { id: reportId },
|
||||
include: {
|
||||
topic: {
|
||||
include: {
|
||||
topicChannels: { include: { channel: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!report) {
|
||||
throw new Error(`Report ${reportId} not found`);
|
||||
}
|
||||
|
||||
const channels = report.topic.topicChannels
|
||||
.map((tc) => tc.channel)
|
||||
.filter((c) => c.enabled);
|
||||
|
||||
logger.info(`开始分发报告到 ${channels.length} 个渠道`);
|
||||
|
||||
for (const channel of channels) {
|
||||
await this.distributeReport(reportId, channel.id);
|
||||
}
|
||||
|
||||
logger.info('报告分发完成');
|
||||
}
|
||||
|
||||
private buildReportUrl(reportId: number): string {
|
||||
const baseUrl = process.env.WEB_BASE_URL || `http://localhost:${config.port}`;
|
||||
return `${baseUrl}/reports/${reportId}`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
import { Article } from '@prisma/client';
|
||||
import { LlmClient } from '../utils/llm-client';
|
||||
import { LlmClientConfig } from '../types/llm';
|
||||
import { ProcessMode, ProcessedContent } from '../types';
|
||||
import logger from '../utils/logger';
|
||||
|
||||
export class ProcessorService {
|
||||
/**
|
||||
* 处理资讯列表
|
||||
*/
|
||||
async processArticles(
|
||||
articles: Article[],
|
||||
mode: ProcessMode,
|
||||
llmConfig?: LlmClientConfig
|
||||
): Promise<ProcessedContent> {
|
||||
logger.info(`开始处理 ${articles.length} 条资讯,模式: ${mode}`);
|
||||
|
||||
switch (mode) {
|
||||
case 'aggregate':
|
||||
return this.aggregateArticles(articles);
|
||||
case 'summary':
|
||||
if (!llmConfig) throw new Error('Summary mode requires LLM config');
|
||||
return this.summarizeArticles(articles, llmConfig);
|
||||
case 'deep_analysis':
|
||||
if (!llmConfig) throw new Error('Deep analysis mode requires LLM config');
|
||||
return this.deepAnalyzeArticles(articles, llmConfig);
|
||||
default:
|
||||
throw new Error(`Unknown process mode: ${mode}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 简单聚合:按主题分类列出标题和链接
|
||||
*/
|
||||
private async aggregateArticles(articles: Article[]): Promise<ProcessedContent> {
|
||||
const lines: string[] = [];
|
||||
|
||||
articles.forEach((article, index) => {
|
||||
lines.push(`${index + 1}. **${article.title}**`);
|
||||
if (article.url) {
|
||||
lines.push(` 链接: ${article.url}`);
|
||||
}
|
||||
if (article.publishedAt) {
|
||||
lines.push(` 发布时间: ${article.publishedAt.toLocaleString('zh-CN')}`);
|
||||
}
|
||||
lines.push('');
|
||||
});
|
||||
|
||||
return {
|
||||
content: lines.join('\n'),
|
||||
mode: 'aggregate',
|
||||
articlesCount: articles.length,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* AI 摘要:对每条资讯生成简短摘要
|
||||
*/
|
||||
private async summarizeArticles(
|
||||
articles: Article[],
|
||||
llmConfig: LlmClientConfig
|
||||
): Promise<ProcessedContent> {
|
||||
const llmClient = new LlmClient(llmConfig);
|
||||
const lines: string[] = [];
|
||||
|
||||
for (const article of articles) {
|
||||
try {
|
||||
const summary = await this.summarizeSingleArticle(article, llmClient);
|
||||
lines.push(`### ${article.title}`);
|
||||
lines.push('');
|
||||
lines.push(summary);
|
||||
lines.push('');
|
||||
if (article.url) {
|
||||
lines.push(`[查看原文](${article.url})`);
|
||||
lines.push('');
|
||||
}
|
||||
lines.push('---');
|
||||
lines.push('');
|
||||
} catch (error) {
|
||||
logger.warn('摘要生成失败', { title: article.title, error });
|
||||
lines.push(`### ${article.title}`);
|
||||
lines.push('');
|
||||
if (article.content) {
|
||||
lines.push(article.content.substring(0, 200) + '...');
|
||||
}
|
||||
lines.push('');
|
||||
if (article.url) {
|
||||
lines.push(`[查看原文](${article.url})`);
|
||||
lines.push('');
|
||||
}
|
||||
lines.push('---');
|
||||
lines.push('');
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
content: lines.join('\n'),
|
||||
mode: 'summary',
|
||||
articlesCount: articles.length,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 为单条资讯生成摘要
|
||||
*/
|
||||
private async summarizeSingleArticle(
|
||||
article: Article,
|
||||
llmClient: LlmClient
|
||||
): Promise<string> {
|
||||
const prompt = `请为以下资讯生成一个简短的摘要(100字以内):
|
||||
|
||||
标题:${article.title}
|
||||
${article.content ? `内容:${article.content.substring(0, 1000)}` : ''}
|
||||
|
||||
要求:
|
||||
1. 提取核心信息
|
||||
2. 简洁明了
|
||||
3. 使用中文`;
|
||||
|
||||
const response = await llmClient.chat(
|
||||
[{ role: 'user', content: prompt }],
|
||||
{
|
||||
temperature: 0.3,
|
||||
maxTokens: 200,
|
||||
}
|
||||
);
|
||||
|
||||
return response.content.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* AI 深度整理:分析、去重、归纳要点,生成结构化报告
|
||||
*/
|
||||
private async deepAnalyzeArticles(
|
||||
articles: Article[],
|
||||
llmConfig: LlmClientConfig
|
||||
): Promise<ProcessedContent> {
|
||||
const llmClient = new LlmClient(llmConfig);
|
||||
|
||||
const articlesList = articles
|
||||
.map((article, index) => {
|
||||
return `[${index + 1}] ${article.title}
|
||||
${article.content ? article.content.substring(0, 500) : ''}
|
||||
${article.url ? `链接: ${article.url}` : ''}
|
||||
---`;
|
||||
})
|
||||
.join('\n\n');
|
||||
|
||||
const prompt = `你是一个专业的资讯分析师。请对以下资讯进行深度分析和整理:
|
||||
|
||||
${articlesList}
|
||||
|
||||
请按以下要求生成报告:
|
||||
|
||||
1. **核心主题**:识别这些资讯的主要主题和趋势
|
||||
2. **重点资讯**:挑选出最重要的 3-5 条资讯,说明为什么重要
|
||||
3. **关键要点**:提炼出关键信息和洞察
|
||||
4. **相关性分析**:如果有相关或重复的资讯,进行合并说明
|
||||
5. **总结**:用 2-3 句话总结整体情况
|
||||
|
||||
要求:
|
||||
- 使用 Markdown 格式
|
||||
- 结构清晰,层次分明
|
||||
- 保留重要资讯的原文链接
|
||||
- 使用中文`;
|
||||
|
||||
const response = await llmClient.chat(
|
||||
[{ role: 'user', content: prompt }],
|
||||
{
|
||||
temperature: 0.5,
|
||||
maxTokens: 2000,
|
||||
}
|
||||
);
|
||||
|
||||
return {
|
||||
content: response.content.trim(),
|
||||
mode: 'deep_analysis',
|
||||
articlesCount: articles.length,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 去重:基于 URL 和标题相似度
|
||||
*/
|
||||
deduplicateArticles(articles: Article[]): Article[] {
|
||||
const seen = new Set<string>();
|
||||
const deduplicated: Article[] = [];
|
||||
|
||||
for (const article of articles) {
|
||||
if (article.url) {
|
||||
if (seen.has(article.url)) {
|
||||
continue;
|
||||
}
|
||||
seen.add(article.url);
|
||||
}
|
||||
|
||||
const normalizedTitle = article.title.toLowerCase().trim();
|
||||
if (seen.has(normalizedTitle)) {
|
||||
continue;
|
||||
}
|
||||
seen.add(normalizedTitle);
|
||||
|
||||
deduplicated.push(article);
|
||||
}
|
||||
|
||||
logger.info(`去重完成: ${articles.length} -> ${deduplicated.length}`);
|
||||
|
||||
return deduplicated;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按发布时间排序
|
||||
*/
|
||||
sortArticlesByDate(articles: Article[], order: 'asc' | 'desc' = 'desc'): Article[] {
|
||||
return [...articles].sort((a, b) => {
|
||||
const dateA = a.publishedAt || a.collectedAt;
|
||||
const dateB = b.publishedAt || b.collectedAt;
|
||||
|
||||
if (order === 'desc') {
|
||||
return dateB.getTime() - dateA.getTime();
|
||||
} else {
|
||||
return dateA.getTime() - dateB.getTime();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
import prisma from '../config/database';
|
||||
import { ProcessorService } from './processor.service';
|
||||
import { ProcessMode, ReportGenerationOptions } from '../types';
|
||||
import { Article } from '@prisma/client';
|
||||
import logger from '../utils/logger';
|
||||
|
||||
export class ReportService {
|
||||
private processorService: ProcessorService;
|
||||
|
||||
constructor() {
|
||||
this.processorService = new ProcessorService();
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成报告
|
||||
*/
|
||||
async generateReport(options: ReportGenerationOptions): Promise<number> {
|
||||
const { topicId, periodStart, periodEnd } = options;
|
||||
|
||||
logger.info('开始生成报告', { topicId, periodStart, periodEnd });
|
||||
|
||||
// 创建报告记录(状态:pending)
|
||||
const report = await prisma.report.create({
|
||||
data: {
|
||||
topicId,
|
||||
title: '',
|
||||
content: '',
|
||||
periodStart,
|
||||
periodEnd,
|
||||
status: 'pending',
|
||||
articleCount: 0,
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
// 更新状态为 generating
|
||||
await prisma.report.update({
|
||||
where: { id: report.id },
|
||||
data: { status: 'generating' },
|
||||
});
|
||||
|
||||
// 查询主题配置
|
||||
const topic = await prisma.topic.findUnique({
|
||||
where: { id: topicId },
|
||||
include: {
|
||||
llmConfig: true,
|
||||
topicSources: {
|
||||
include: { source: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!topic) {
|
||||
throw new Error(`Topic ${topicId} not found`);
|
||||
}
|
||||
|
||||
if (!topic.enabled) {
|
||||
throw new Error(`Topic ${topic.name} is disabled`);
|
||||
}
|
||||
|
||||
// 查询资讯
|
||||
const sourceIds = topic.topicSources.map((ts) => ts.sourceId);
|
||||
const articles = await this.queryArticles(sourceIds, periodStart, periodEnd);
|
||||
|
||||
if (articles.length === 0) {
|
||||
logger.warn('没有找到资讯', { topicId, periodStart, periodEnd });
|
||||
|
||||
await prisma.report.update({
|
||||
where: { id: report.id },
|
||||
data: {
|
||||
title: `${topic.name} - ${this.formatDateRange(periodStart, periodEnd)}`,
|
||||
content: '本期没有新的资讯。',
|
||||
status: 'completed',
|
||||
articleCount: 0,
|
||||
},
|
||||
});
|
||||
|
||||
return report.id;
|
||||
}
|
||||
|
||||
logger.info(`找到 ${articles.length} 条资讯`);
|
||||
|
||||
// 去重和排序
|
||||
const deduplicated = this.processorService.deduplicateArticles(articles);
|
||||
const sorted = this.processorService.sortArticlesByDate(deduplicated);
|
||||
|
||||
logger.info(`去重后 ${sorted.length} 条资讯`);
|
||||
|
||||
// 处理内容
|
||||
let processedContent: string;
|
||||
|
||||
if (!topic.llmConfig || !topic.llmConfig.enabled) {
|
||||
logger.warn('没有启用的 LLM 配置,使用简单聚合模式');
|
||||
const result = await this.processorService.processArticles(sorted, 'aggregate');
|
||||
processedContent = result.content;
|
||||
} else {
|
||||
const result = await this.processorService.processArticles(
|
||||
sorted,
|
||||
topic.processMode as ProcessMode,
|
||||
{
|
||||
baseUrl: topic.llmConfig.baseUrl,
|
||||
model: topic.llmConfig.model,
|
||||
apiKey: topic.llmConfig.apiKey,
|
||||
}
|
||||
);
|
||||
processedContent = result.content;
|
||||
}
|
||||
|
||||
// 生成报告标题和内容
|
||||
const title = `${topic.name} - ${this.formatDateRange(periodStart, periodEnd)}`;
|
||||
const fullContent = this.buildReportContent(
|
||||
title,
|
||||
topic.name,
|
||||
periodStart,
|
||||
periodEnd,
|
||||
sorted.length,
|
||||
processedContent
|
||||
);
|
||||
|
||||
// 更新报告
|
||||
await prisma.report.update({
|
||||
where: { id: report.id },
|
||||
data: {
|
||||
title,
|
||||
content: fullContent,
|
||||
status: 'completed',
|
||||
articleCount: sorted.length,
|
||||
},
|
||||
});
|
||||
|
||||
logger.info(`报告生成完成: ${report.id}`);
|
||||
return report.id;
|
||||
} catch (error) {
|
||||
logger.error('报告生成失败', { reportId: report.id, error });
|
||||
|
||||
await prisma.report.update({
|
||||
where: { id: report.id },
|
||||
data: {
|
||||
status: 'failed',
|
||||
errorMessage: error instanceof Error ? error.message : 'Unknown error',
|
||||
},
|
||||
});
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询资讯
|
||||
*/
|
||||
private async queryArticles(
|
||||
sourceIds: number[],
|
||||
periodStart: Date,
|
||||
periodEnd: Date
|
||||
): Promise<Article[]> {
|
||||
return prisma.article.findMany({
|
||||
where: {
|
||||
sourceId: { in: sourceIds },
|
||||
OR: [
|
||||
{
|
||||
publishedAt: { gte: periodStart, lte: periodEnd },
|
||||
},
|
||||
{
|
||||
publishedAt: null,
|
||||
collectedAt: { gte: periodStart, lte: periodEnd },
|
||||
},
|
||||
],
|
||||
},
|
||||
orderBy: [{ publishedAt: 'desc' }, { collectedAt: 'desc' }],
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建报告内容
|
||||
*/
|
||||
private buildReportContent(
|
||||
title: string,
|
||||
topicName: string,
|
||||
periodStart: Date,
|
||||
periodEnd: Date,
|
||||
articleCount: number,
|
||||
processedContent: string
|
||||
): string {
|
||||
return `# ${title}
|
||||
|
||||
**主题**: ${topicName}
|
||||
**时间范围**: ${this.formatDate(periodStart)} - ${this.formatDate(periodEnd)}
|
||||
**资讯数量**: ${articleCount} 条
|
||||
**生成时间**: ${this.formatDate(new Date())}
|
||||
|
||||
---
|
||||
|
||||
${processedContent}
|
||||
|
||||
---
|
||||
|
||||
*本报告由 News Aggregator 自动生成*`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化日期范围
|
||||
*/
|
||||
private formatDateRange(start: Date, end: Date): string {
|
||||
const startStr = this.formatDate(start);
|
||||
const endStr = this.formatDate(end);
|
||||
return startStr === endStr ? startStr : `${startStr} 至 ${endStr}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化日期
|
||||
*/
|
||||
private formatDate(date: Date): string {
|
||||
return date.toLocaleDateString('zh-CN', {
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据主题配置计算时间范围
|
||||
*/
|
||||
calculatePeriod(scheduleConfig: any): { start: Date; end: Date } {
|
||||
const now = new Date();
|
||||
const lookback = scheduleConfig.lookback || 24;
|
||||
const start = new Date(now.getTime() - lookback * 60 * 60 * 1000);
|
||||
return { start, end: now };
|
||||
}
|
||||
|
||||
/**
|
||||
* 为主题生成报告
|
||||
*/
|
||||
async generateReportForTopic(topicId: number): Promise<number> {
|
||||
const topic = await prisma.topic.findUnique({ where: { id: topicId } });
|
||||
|
||||
if (!topic) {
|
||||
throw new Error(`Topic ${topicId} not found`);
|
||||
}
|
||||
|
||||
const { start, end } = this.calculatePeriod(topic.scheduleConfig);
|
||||
|
||||
return this.generateReport({
|
||||
topicId,
|
||||
periodStart: start,
|
||||
periodEnd: end,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 为所有启用的主题生成报告
|
||||
*/
|
||||
async generateReportsForAllTopics(): Promise<number[]> {
|
||||
const topics = await prisma.topic.findMany({ where: { enabled: true } });
|
||||
|
||||
logger.info(`开始为 ${topics.length} 个主题生成报告`);
|
||||
|
||||
const reportIds: number[] = [];
|
||||
|
||||
for (const topic of topics) {
|
||||
try {
|
||||
const reportId = await this.generateReportForTopic(topic.id);
|
||||
reportIds.push(reportId);
|
||||
} catch (error) {
|
||||
logger.error(`主题 ${topic.name} 报告生成失败`, error);
|
||||
}
|
||||
}
|
||||
|
||||
logger.info(`报告生成完成,成功 ${reportIds.length}/${topics.length}`);
|
||||
return reportIds;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取报告详情
|
||||
*/
|
||||
async getReport(reportId: number) {
|
||||
return prisma.report.findUnique({
|
||||
where: { id: reportId },
|
||||
include: { topic: true },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取报告列表
|
||||
*/
|
||||
async getReports(options: {
|
||||
topicId?: number;
|
||||
status?: string;
|
||||
page?: number;
|
||||
limit?: number;
|
||||
}) {
|
||||
const { topicId, status, page = 1, limit = 20 } = options;
|
||||
|
||||
const where: any = {};
|
||||
if (topicId) where.topicId = topicId;
|
||||
if (status) where.status = status;
|
||||
|
||||
const [items, total] = await Promise.all([
|
||||
prisma.report.findMany({
|
||||
where,
|
||||
include: { topic: true },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
skip: (page - 1) * limit,
|
||||
take: limit,
|
||||
}),
|
||||
prisma.report.count({ where }),
|
||||
]);
|
||||
|
||||
return {
|
||||
items,
|
||||
total,
|
||||
page,
|
||||
limit,
|
||||
totalPages: Math.ceil(total / limit),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import cron, { ScheduledTask } from 'node-cron';
|
||||
import { CollectorService } from './collector.service';
|
||||
import { ReportService } from './report.service';
|
||||
import { DistributorService } from './distributor.service';
|
||||
import prisma from '../config/database';
|
||||
import logger from '../utils/logger';
|
||||
|
||||
interface ScheduledTaskInfo {
|
||||
id: string;
|
||||
type: 'collection' | 'report';
|
||||
cronExpression: string;
|
||||
task: ScheduledTask;
|
||||
resourceId: number;
|
||||
}
|
||||
|
||||
export class SchedulerService {
|
||||
private tasks: Map<string, ScheduledTaskInfo> = new Map();
|
||||
private collectorService: CollectorService;
|
||||
private reportService: ReportService;
|
||||
private distributorService: DistributorService;
|
||||
|
||||
constructor() {
|
||||
this.collectorService = new CollectorService();
|
||||
this.reportService = new ReportService();
|
||||
this.distributorService = new DistributorService();
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
logger.info('启动调度器...');
|
||||
await this.loadCollectionTasks();
|
||||
await this.loadReportTasks();
|
||||
logger.info(`调度器启动完成,共 ${this.tasks.size} 个任务`);
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
logger.info('停止调度器...');
|
||||
this.tasks.forEach((task) => task.task.stop());
|
||||
this.tasks.clear();
|
||||
logger.info('调度器已停止');
|
||||
}
|
||||
|
||||
private async loadCollectionTasks(): Promise<void> {
|
||||
const sources = await prisma.source.findMany({ where: { enabled: true } });
|
||||
logger.info(`加载 ${sources.length} 个采集任务`);
|
||||
|
||||
for (const source of sources) {
|
||||
this.scheduleCollectionTask(source.id, source.cronExpression);
|
||||
}
|
||||
}
|
||||
|
||||
private async loadReportTasks(): Promise<void> {
|
||||
const topics = await prisma.topic.findMany({ where: { enabled: true } });
|
||||
logger.info(`加载 ${topics.length} 个报告生成任务`);
|
||||
|
||||
for (const topic of topics) {
|
||||
const scheduleConfig = topic.scheduleConfig as any;
|
||||
if (scheduleConfig?.cron) {
|
||||
this.scheduleReportTask(topic.id, scheduleConfig.cron);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
scheduleCollectionTask(sourceId: number, cronExpression: string): void {
|
||||
const taskId = `collection-${sourceId}`;
|
||||
|
||||
if (this.tasks.has(taskId)) {
|
||||
this.unscheduleTask(taskId);
|
||||
}
|
||||
|
||||
if (!cron.validate(cronExpression)) {
|
||||
logger.error(`无效的 cron 表达式: ${cronExpression}`, { sourceId });
|
||||
return;
|
||||
}
|
||||
|
||||
const task = cron.schedule(cronExpression, async () => {
|
||||
logger.info(`执行采集任务: sourceId=${sourceId}`);
|
||||
try {
|
||||
await this.collectorService.collectSource(sourceId);
|
||||
} catch (error) {
|
||||
logger.error('采集任务执行失败', { sourceId, error });
|
||||
}
|
||||
});
|
||||
|
||||
this.tasks.set(taskId, {
|
||||
id: taskId,
|
||||
type: 'collection',
|
||||
cronExpression,
|
||||
task,
|
||||
resourceId: sourceId,
|
||||
});
|
||||
|
||||
logger.info(`采集任务已调度: sourceId=${sourceId}, cron=${cronExpression}`);
|
||||
}
|
||||
|
||||
scheduleReportTask(topicId: number, cronExpression: string): void {
|
||||
const taskId = `report-${topicId}`;
|
||||
|
||||
if (this.tasks.has(taskId)) {
|
||||
this.unscheduleTask(taskId);
|
||||
}
|
||||
|
||||
if (!cron.validate(cronExpression)) {
|
||||
logger.error(`无效的 cron 表达式: ${cronExpression}`, { topicId });
|
||||
return;
|
||||
}
|
||||
|
||||
const task = cron.schedule(cronExpression, async () => {
|
||||
logger.info(`执行报告生成任务: topicId=${topicId}`);
|
||||
try {
|
||||
const reportId = await this.reportService.generateReportForTopic(topicId);
|
||||
await this.distributorService.distributeReportToAllChannels(reportId);
|
||||
} catch (error) {
|
||||
logger.error('报告生成任务执行失败', { topicId, error });
|
||||
}
|
||||
});
|
||||
|
||||
this.tasks.set(taskId, {
|
||||
id: taskId,
|
||||
type: 'report',
|
||||
cronExpression,
|
||||
task,
|
||||
resourceId: topicId,
|
||||
});
|
||||
|
||||
logger.info(`报告生成任务已调度: topicId=${topicId}, cron=${cronExpression}`);
|
||||
}
|
||||
|
||||
unscheduleTask(taskId: string): void {
|
||||
const scheduledTask = this.tasks.get(taskId);
|
||||
if (scheduledTask) {
|
||||
scheduledTask.task.stop();
|
||||
this.tasks.delete(taskId);
|
||||
logger.info(`任务已取消: ${taskId}`);
|
||||
}
|
||||
}
|
||||
|
||||
async reload(): Promise<void> {
|
||||
logger.info('重新加载调度任务...');
|
||||
this.stop();
|
||||
await this.start();
|
||||
}
|
||||
|
||||
getTasksStatus(): Array<{
|
||||
id: string;
|
||||
type: string;
|
||||
cronExpression: string;
|
||||
resourceId: number;
|
||||
}> {
|
||||
return Array.from(this.tasks.values()).map((task) => ({
|
||||
id: task.id,
|
||||
type: task.type,
|
||||
cronExpression: task.cronExpression,
|
||||
resourceId: task.resourceId,
|
||||
}));
|
||||
}
|
||||
|
||||
async triggerCollection(sourceId: number): Promise<void> {
|
||||
logger.info(`手动触发采集任务: sourceId=${sourceId}`);
|
||||
await this.collectorService.collectSource(sourceId);
|
||||
}
|
||||
|
||||
async triggerReport(topicId: number): Promise<number> {
|
||||
logger.info(`手动触发报告生成任务: topicId=${topicId}`);
|
||||
const reportId = await this.reportService.generateReportForTopic(topicId);
|
||||
await this.distributorService.distributeReportToAllChannels(reportId);
|
||||
return reportId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
// 采集器类型定义
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
// API 采集器配置
|
||||
export interface ApiCollectorConfig {
|
||||
url: string;
|
||||
method?: 'GET' | 'POST';
|
||||
headers?: Record<string, string>;
|
||||
params?: Record<string, any>;
|
||||
body?: any;
|
||||
dataPath?: string;
|
||||
mapping: {
|
||||
title: string;
|
||||
content?: string;
|
||||
url?: string;
|
||||
publishedAt?: string;
|
||||
};
|
||||
}
|
||||
|
||||
// Playwright 采集器配置
|
||||
export interface PlaywrightCollectorConfig {
|
||||
url: string;
|
||||
selectors: {
|
||||
items: string;
|
||||
title: string;
|
||||
content?: string;
|
||||
url?: string;
|
||||
publishedAt?: string;
|
||||
};
|
||||
waitFor?: string;
|
||||
waitTimeout?: number;
|
||||
script?: string;
|
||||
}
|
||||
|
||||
// RSS 采集器配置
|
||||
export interface RssCollectorConfig {
|
||||
url: string;
|
||||
customFields?: {
|
||||
item?: string[];
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// 分发器类型定义
|
||||
|
||||
export type DistributorType = 'email' | 'dingtalk' | 'wechat' | 'slack';
|
||||
|
||||
export interface DistributorConfig {
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
export interface DistributionResult {
|
||||
success: boolean;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface ReportSummary {
|
||||
title: string;
|
||||
topicName: string;
|
||||
articleCount: number;
|
||||
periodStart: Date;
|
||||
periodEnd: Date;
|
||||
webUrl: string;
|
||||
}
|
||||
|
||||
// 邮件配置
|
||||
export interface EmailDistributorConfig {
|
||||
smtp: {
|
||||
host: string;
|
||||
port: number;
|
||||
secure: boolean;
|
||||
auth: {
|
||||
user: string;
|
||||
pass: string;
|
||||
};
|
||||
};
|
||||
from: string;
|
||||
to: string[];
|
||||
}
|
||||
|
||||
// 钉钉配置
|
||||
export interface DingtalkDistributorConfig {
|
||||
webhook: string;
|
||||
secret?: string;
|
||||
}
|
||||
|
||||
// 企业微信配置
|
||||
export interface WechatDistributorConfig {
|
||||
webhook: string;
|
||||
}
|
||||
|
||||
// Slack 配置
|
||||
export interface SlackDistributorConfig {
|
||||
webhook: string;
|
||||
}
|
||||
+13
-19
@@ -21,29 +21,23 @@ export interface PaginatedResponse<T> extends ApiResponse<T[]> {
|
||||
};
|
||||
}
|
||||
|
||||
// 采集器类型
|
||||
export interface CollectorConfig {
|
||||
url: string;
|
||||
method?: 'GET' | 'POST';
|
||||
headers?: Record<string, string>;
|
||||
body?: any;
|
||||
}
|
||||
|
||||
export interface RawArticle {
|
||||
title: string;
|
||||
content?: string;
|
||||
url?: string;
|
||||
publishedAt?: Date;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
// 处理器类型
|
||||
export type ProcessMode = 'aggregate' | 'summary' | 'deep_analysis';
|
||||
|
||||
export interface ProcessingResult {
|
||||
title: string;
|
||||
export interface ProcessedContent {
|
||||
content: string;
|
||||
articleCount: number;
|
||||
mode: ProcessMode;
|
||||
articlesCount: number;
|
||||
}
|
||||
|
||||
// 报告类型
|
||||
export type ReportStatus = 'pending' | 'generating' | 'completed' | 'failed';
|
||||
|
||||
export interface ReportGenerationOptions {
|
||||
topicId: number;
|
||||
periodStart: Date;
|
||||
periodEnd: Date;
|
||||
manualTrigger?: boolean;
|
||||
}
|
||||
|
||||
// 推送器类型
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
// LLM 类型定义
|
||||
|
||||
export interface LlmMessage {
|
||||
role: 'system' | 'user' | 'assistant';
|
||||
content: string;
|
||||
}
|
||||
|
||||
export interface LlmResponse {
|
||||
content: string;
|
||||
usage?: {
|
||||
promptTokens: number;
|
||||
completionTokens: number;
|
||||
totalTokens: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface LlmClientConfig {
|
||||
baseUrl: string;
|
||||
model: string;
|
||||
apiKey: string;
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import OpenAI from 'openai';
|
||||
import { LlmClientConfig, LlmMessage, LlmResponse } from '../types/llm';
|
||||
import logger from './logger';
|
||||
|
||||
export class LlmClient {
|
||||
private client: OpenAI;
|
||||
private model: string;
|
||||
|
||||
constructor(private config: LlmClientConfig) {
|
||||
this.client = new OpenAI({
|
||||
baseURL: config.baseUrl,
|
||||
apiKey: config.apiKey,
|
||||
});
|
||||
this.model = config.model;
|
||||
}
|
||||
|
||||
async chat(
|
||||
messages: LlmMessage[],
|
||||
options?: {
|
||||
temperature?: number;
|
||||
maxTokens?: number;
|
||||
}
|
||||
): Promise<LlmResponse> {
|
||||
try {
|
||||
logger.debug('调用 LLM', {
|
||||
model: this.model,
|
||||
messagesCount: messages.length,
|
||||
});
|
||||
|
||||
const response = await this.client.chat.completions.create({
|
||||
model: this.model,
|
||||
messages: messages as any,
|
||||
temperature: options?.temperature ?? 0.7,
|
||||
max_tokens: options?.maxTokens,
|
||||
});
|
||||
|
||||
const content = response.choices[0]?.message?.content || '';
|
||||
|
||||
logger.debug('LLM 响应完成', {
|
||||
contentLength: content.length,
|
||||
usage: response.usage,
|
||||
});
|
||||
|
||||
return {
|
||||
content,
|
||||
usage: response.usage
|
||||
? {
|
||||
promptTokens: response.usage.prompt_tokens,
|
||||
completionTokens: response.usage.completion_tokens,
|
||||
totalTokens: response.usage.total_tokens,
|
||||
}
|
||||
: undefined,
|
||||
};
|
||||
} catch (error) {
|
||||
logger.error('LLM 调用失败', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async streamChat(
|
||||
messages: LlmMessage[],
|
||||
onChunk: (chunk: string) => void,
|
||||
options?: {
|
||||
temperature?: number;
|
||||
maxTokens?: number;
|
||||
}
|
||||
): Promise<void> {
|
||||
try {
|
||||
logger.debug('调用 LLM (流式)', {
|
||||
model: this.model,
|
||||
messagesCount: messages.length,
|
||||
});
|
||||
|
||||
const stream = await this.client.chat.completions.create({
|
||||
model: this.model,
|
||||
messages: messages as any,
|
||||
temperature: options?.temperature ?? 0.7,
|
||||
max_tokens: options?.maxTokens,
|
||||
stream: true,
|
||||
});
|
||||
|
||||
for await (const chunk of stream) {
|
||||
const content = chunk.choices[0]?.delta?.content || '';
|
||||
if (content) {
|
||||
onChunk(content);
|
||||
}
|
||||
}
|
||||
|
||||
logger.debug('LLM 流式响应完成');
|
||||
} catch (error) {
|
||||
logger.error('LLM 流式调用失败', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { FastifyError, FastifyReply, FastifyRequest } from 'fastify';
|
||||
import { AppError, ValidationError } from '../../utils/errors';
|
||||
import logger from '../../utils/logger';
|
||||
|
||||
export async function errorHandler(
|
||||
error: FastifyError,
|
||||
request: FastifyRequest,
|
||||
reply: FastifyReply
|
||||
): Promise<void> {
|
||||
logger.error('请求处理错误:', {
|
||||
method: request.method,
|
||||
url: request.url,
|
||||
error: error.message,
|
||||
stack: error.stack,
|
||||
});
|
||||
|
||||
// 处理自定义应用错误
|
||||
if (error instanceof AppError) {
|
||||
const response: any = {
|
||||
success: false,
|
||||
error: error.message,
|
||||
};
|
||||
|
||||
// 如果是验证错误,附加详细信息
|
||||
if (error instanceof ValidationError) {
|
||||
response.details = error.errors;
|
||||
}
|
||||
|
||||
reply.status(error.statusCode).send(response);
|
||||
return;
|
||||
}
|
||||
|
||||
// 处理 Fastify 验证错误
|
||||
if (error.validation) {
|
||||
reply.status(400).send({
|
||||
success: false,
|
||||
error: '请求参数验证失败',
|
||||
details: error.validation,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// 处理未知错误
|
||||
const statusCode = error.statusCode || 500;
|
||||
const message = statusCode === 500 ? '服务器内部错误' : error.message;
|
||||
|
||||
reply.status(statusCode).send({
|
||||
success: false,
|
||||
error: message,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { FastifyRequest, FastifyReply, HookHandlerDoneFunction } from 'fastify';
|
||||
import logger from '../../utils/logger';
|
||||
|
||||
export function requestLogger(
|
||||
request: FastifyRequest,
|
||||
reply: FastifyReply,
|
||||
done: HookHandlerDoneFunction
|
||||
): void {
|
||||
const start = Date.now();
|
||||
|
||||
// 记录请求开始
|
||||
logger.debug(`--> ${request.method} ${request.url}`);
|
||||
|
||||
// 在响应发送后记录
|
||||
reply.raw.on('finish', () => {
|
||||
const duration = Date.now() - start;
|
||||
const statusCode = reply.statusCode;
|
||||
|
||||
// 根据状态码选择日志级别
|
||||
if (statusCode >= 500) {
|
||||
logger.error(`<-- ${request.method} ${request.url} ${statusCode} ${duration}ms`);
|
||||
} else if (statusCode >= 400) {
|
||||
logger.warn(`<-- ${request.method} ${request.url} ${statusCode} ${duration}ms`);
|
||||
} else {
|
||||
logger.info(`<-- ${request.method} ${request.url} ${statusCode} ${duration}ms`);
|
||||
}
|
||||
});
|
||||
|
||||
done();
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import { FastifyInstance } from 'fastify';
|
||||
import prisma from '../../config/database';
|
||||
import { successResponse, paginatedResponse } from '../../utils/response';
|
||||
import { NotFoundError } from '../../utils/errors';
|
||||
|
||||
export async function articleRoutes(app: FastifyInstance): Promise<void> {
|
||||
// 获取资讯列表
|
||||
app.get('/', async (request, reply) => {
|
||||
const { page = 1, limit = 20, sourceId, topicId, startDate, endDate } = request.query as any;
|
||||
|
||||
const where: any = {};
|
||||
|
||||
if (sourceId) {
|
||||
where.sourceId = parseInt(sourceId);
|
||||
}
|
||||
|
||||
if (topicId) {
|
||||
const topic = await prisma.topic.findUnique({
|
||||
where: { id: parseInt(topicId) },
|
||||
include: { topicSources: true },
|
||||
});
|
||||
|
||||
if (topic) {
|
||||
where.sourceId = { in: topic.topicSources.map((ts) => ts.sourceId) };
|
||||
}
|
||||
}
|
||||
|
||||
if (startDate || endDate) {
|
||||
where.OR = [
|
||||
{
|
||||
publishedAt: {
|
||||
...(startDate && { gte: new Date(startDate) }),
|
||||
...(endDate && { lte: new Date(endDate) }),
|
||||
},
|
||||
},
|
||||
{
|
||||
publishedAt: null,
|
||||
collectedAt: {
|
||||
...(startDate && { gte: new Date(startDate) }),
|
||||
...(endDate && { lte: new Date(endDate) }),
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const [items, total] = await Promise.all([
|
||||
prisma.article.findMany({
|
||||
where,
|
||||
include: { source: true },
|
||||
orderBy: [{ publishedAt: 'desc' }, { collectedAt: 'desc' }],
|
||||
skip: (Number(page) - 1) * Number(limit),
|
||||
take: Number(limit),
|
||||
}),
|
||||
prisma.article.count({ where }),
|
||||
]);
|
||||
|
||||
paginatedResponse(reply, items, total, Number(page), Number(limit));
|
||||
});
|
||||
|
||||
// 获取单个资讯
|
||||
app.get('/:id', async (request, reply) => {
|
||||
const { id } = request.params as any;
|
||||
|
||||
const article = await prisma.article.findUnique({
|
||||
where: { id: parseInt(id) },
|
||||
include: { source: true },
|
||||
});
|
||||
|
||||
if (!article) {
|
||||
throw new NotFoundError('资讯不存在');
|
||||
}
|
||||
|
||||
successResponse(reply, article);
|
||||
});
|
||||
|
||||
// 删除资讯
|
||||
app.delete('/:id', async (request, reply) => {
|
||||
const { id } = request.params as any;
|
||||
|
||||
const existing = await prisma.article.findUnique({
|
||||
where: { id: parseInt(id) },
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
throw new NotFoundError('资讯不存在');
|
||||
}
|
||||
|
||||
await prisma.article.delete({ where: { id: parseInt(id) } });
|
||||
|
||||
successResponse(reply, null, '资讯删除成功');
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import { FastifyInstance } from 'fastify';
|
||||
import prisma from '../../config/database';
|
||||
import { successResponse, paginatedResponse } from '../../utils/response';
|
||||
import { NotFoundError, BadRequestError } from '../../utils/errors';
|
||||
|
||||
export async function channelRoutes(app: FastifyInstance): Promise<void> {
|
||||
// 获取推送渠道列表
|
||||
app.get('/', async (request, reply) => {
|
||||
const { page = 1, limit = 20, type } = request.query as any;
|
||||
|
||||
const where: any = {};
|
||||
if (type) where.type = type;
|
||||
|
||||
const [items, total] = await Promise.all([
|
||||
prisma.channel.findMany({
|
||||
where,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
skip: (Number(page) - 1) * Number(limit),
|
||||
take: Number(limit),
|
||||
}),
|
||||
prisma.channel.count({ where }),
|
||||
]);
|
||||
|
||||
paginatedResponse(reply, items, total, Number(page), Number(limit));
|
||||
});
|
||||
|
||||
// 获取单个推送渠道
|
||||
app.get('/:id', async (request, reply) => {
|
||||
const { id } = request.params as any;
|
||||
|
||||
const channel = await prisma.channel.findUnique({
|
||||
where: { id: parseInt(id) },
|
||||
include: {
|
||||
topicChannels: { include: { topic: true } },
|
||||
},
|
||||
});
|
||||
|
||||
if (!channel) {
|
||||
throw new NotFoundError('推送渠道不存在');
|
||||
}
|
||||
|
||||
successResponse(reply, channel);
|
||||
});
|
||||
|
||||
// 创建推送渠道
|
||||
app.post('/', async (request, reply) => {
|
||||
const { name, type, config, enabled } = request.body as any;
|
||||
|
||||
if (!name || !type || !config) {
|
||||
throw new BadRequestError('缺少必填字段');
|
||||
}
|
||||
|
||||
const channel = await prisma.channel.create({
|
||||
data: { name, type, config, enabled: enabled ?? true },
|
||||
});
|
||||
|
||||
successResponse(reply, channel, '推送渠道创建成功', 201);
|
||||
});
|
||||
|
||||
// 更新推送渠道
|
||||
app.put('/:id', async (request, reply) => {
|
||||
const { id } = request.params as any;
|
||||
const { name, type, config, enabled } = request.body as any;
|
||||
|
||||
const existing = await prisma.channel.findUnique({
|
||||
where: { id: parseInt(id) },
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
throw new NotFoundError('推送渠道不存在');
|
||||
}
|
||||
|
||||
// 构建更新数据对象,只包含提供的字段
|
||||
const updateData: any = {};
|
||||
if (name !== undefined) updateData.name = name;
|
||||
if (type !== undefined) updateData.type = type;
|
||||
if (config !== undefined) updateData.config = config;
|
||||
if (enabled !== undefined) updateData.enabled = enabled;
|
||||
|
||||
const channel = await prisma.channel.update({
|
||||
where: { id: parseInt(id) },
|
||||
data: updateData,
|
||||
});
|
||||
|
||||
successResponse(reply, channel, '推送渠道更新成功');
|
||||
});
|
||||
|
||||
// 删除推送渠道
|
||||
app.delete('/:id', async (request, reply) => {
|
||||
const { id } = request.params as any;
|
||||
|
||||
const existing = await prisma.channel.findUnique({
|
||||
where: { id: parseInt(id) },
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
throw new NotFoundError('推送渠道不存在');
|
||||
}
|
||||
|
||||
await prisma.channel.delete({ where: { id: parseInt(id) } });
|
||||
|
||||
successResponse(reply, null, '推送渠道删除成功');
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { FastifyInstance } from 'fastify';
|
||||
import prisma from '../../config/database';
|
||||
import { successResponse, paginatedResponse } from '../../utils/response';
|
||||
|
||||
export async function collectionLogRoutes(app: FastifyInstance): Promise<void> {
|
||||
// 获取采集日志列表
|
||||
app.get('/', async (request, reply) => {
|
||||
const { page = 1, limit = 20, sourceId, status } = request.query as any;
|
||||
|
||||
const where: any = {};
|
||||
if (sourceId) where.sourceId = parseInt(sourceId);
|
||||
if (status) where.status = status;
|
||||
|
||||
const [items, total] = await Promise.all([
|
||||
prisma.collectionLog.findMany({
|
||||
where,
|
||||
include: { source: true },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
skip: (Number(page) - 1) * Number(limit),
|
||||
take: Number(limit),
|
||||
}),
|
||||
prisma.collectionLog.count({ where }),
|
||||
]);
|
||||
|
||||
paginatedResponse(reply, items, total, Number(page), Number(limit));
|
||||
});
|
||||
|
||||
// 获取数据源统计
|
||||
app.get('/stats', async (request, reply) => {
|
||||
const sources = await prisma.source.findMany({
|
||||
include: {
|
||||
collectionLogs: {
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: 1,
|
||||
},
|
||||
_count: {
|
||||
select: { articles: true, collectionLogs: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const stats = sources.map((source) => ({
|
||||
id: source.id,
|
||||
name: source.name,
|
||||
type: source.type,
|
||||
enabled: source.enabled,
|
||||
lastCollectedAt: source.lastCollectedAt,
|
||||
lastLog: source.collectionLogs[0] || null,
|
||||
totalArticles: source._count.articles,
|
||||
totalCollections: source._count.collectionLogs,
|
||||
}));
|
||||
|
||||
successResponse(reply, stats);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { FastifyInstance } from 'fastify';
|
||||
import prisma from '../../config/database';
|
||||
|
||||
export async function healthRoutes(app: FastifyInstance): Promise<void> {
|
||||
// 基础健康检查
|
||||
app.get('/health', async (request, reply) => {
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
status: 'ok',
|
||||
timestamp: new Date().toISOString(),
|
||||
version: '1.0.0',
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
// 详细健康检查(包括数据库)
|
||||
app.get('/health/detailed', async (request, reply) => {
|
||||
const checks: Record<string, string> = {
|
||||
server: 'ok',
|
||||
};
|
||||
|
||||
// 检查数据库连接
|
||||
try {
|
||||
await prisma.$queryRaw`SELECT 1`;
|
||||
checks.database = 'ok';
|
||||
} catch (error) {
|
||||
checks.database = 'error';
|
||||
}
|
||||
|
||||
const allOk = Object.values(checks).every((v) => v === 'ok');
|
||||
|
||||
return {
|
||||
success: allOk,
|
||||
data: {
|
||||
status: allOk ? 'ok' : 'degraded',
|
||||
timestamp: new Date().toISOString(),
|
||||
version: '1.0.0',
|
||||
checks,
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { FastifyInstance } from 'fastify';
|
||||
import prisma from '../../config/database';
|
||||
import { successResponse, paginatedResponse } from '../../utils/response';
|
||||
import { NotFoundError, BadRequestError } from '../../utils/errors';
|
||||
|
||||
export async function llmConfigRoutes(app: FastifyInstance): Promise<void> {
|
||||
// 获取 LLM 配置列表
|
||||
app.get('/', async (request, reply) => {
|
||||
const { page = 1, limit = 20 } = request.query as any;
|
||||
|
||||
const [items, total] = await Promise.all([
|
||||
prisma.llmConfig.findMany({
|
||||
orderBy: { createdAt: 'desc' },
|
||||
skip: (Number(page) - 1) * Number(limit),
|
||||
take: Number(limit),
|
||||
}),
|
||||
prisma.llmConfig.count(),
|
||||
]);
|
||||
|
||||
paginatedResponse(reply, items, total, Number(page), Number(limit));
|
||||
});
|
||||
|
||||
// 获取单个 LLM 配置
|
||||
app.get('/:id', async (request, reply) => {
|
||||
const { id } = request.params as any;
|
||||
|
||||
const config = await prisma.llmConfig.findUnique({
|
||||
where: { id: parseInt(id) },
|
||||
});
|
||||
|
||||
if (!config) {
|
||||
throw new NotFoundError('LLM 配置不存在');
|
||||
}
|
||||
|
||||
successResponse(reply, config);
|
||||
});
|
||||
|
||||
// 创建 LLM 配置
|
||||
app.post('/', async (request, reply) => {
|
||||
const { name, baseUrl, model, apiKey, enabled } = request.body as any;
|
||||
|
||||
if (!name || !baseUrl || !model || !apiKey) {
|
||||
throw new BadRequestError('缺少必填字段');
|
||||
}
|
||||
|
||||
const config = await prisma.llmConfig.create({
|
||||
data: { name, baseUrl, model, apiKey, enabled: enabled ?? true },
|
||||
});
|
||||
|
||||
successResponse(reply, config, 'LLM 配置创建成功', 201);
|
||||
});
|
||||
|
||||
// 更新 LLM 配置
|
||||
app.put('/:id', async (request, reply) => {
|
||||
const { id } = request.params as any;
|
||||
const { name, baseUrl, model, apiKey, enabled } = request.body as any;
|
||||
|
||||
const existing = await prisma.llmConfig.findUnique({
|
||||
where: { id: parseInt(id) },
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
throw new NotFoundError('LLM 配置不存在');
|
||||
}
|
||||
|
||||
// 构建更新数据对象,只包含提供的字段
|
||||
const updateData: any = {};
|
||||
if (name !== undefined) updateData.name = name;
|
||||
if (baseUrl !== undefined) updateData.baseUrl = baseUrl;
|
||||
if (model !== undefined) updateData.model = model;
|
||||
if (apiKey !== undefined) updateData.apiKey = apiKey;
|
||||
if (enabled !== undefined) updateData.enabled = enabled;
|
||||
|
||||
const config = await prisma.llmConfig.update({
|
||||
where: { id: parseInt(id) },
|
||||
data: updateData,
|
||||
});
|
||||
|
||||
successResponse(reply, config, 'LLM 配置更新成功');
|
||||
});
|
||||
|
||||
// 删除 LLM 配置
|
||||
app.delete('/:id', async (request, reply) => {
|
||||
const { id } = request.params as any;
|
||||
|
||||
const existing = await prisma.llmConfig.findUnique({
|
||||
where: { id: parseInt(id) },
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
throw new NotFoundError('LLM 配置不存在');
|
||||
}
|
||||
|
||||
await prisma.llmConfig.delete({ where: { id: parseInt(id) } });
|
||||
|
||||
successResponse(reply, null, 'LLM 配置删除成功');
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { FastifyInstance } from 'fastify';
|
||||
import prisma from '../../config/database';
|
||||
import { successResponse, paginatedResponse } from '../../utils/response';
|
||||
import { NotFoundError } from '../../utils/errors';
|
||||
|
||||
export async function reportRoutes(app: FastifyInstance): Promise<void> {
|
||||
// 获取报告列表
|
||||
app.get('/', async (request, reply) => {
|
||||
const { page = 1, limit = 20, topicId, status } = request.query as any;
|
||||
|
||||
const where: any = {};
|
||||
if (topicId) where.topicId = parseInt(topicId);
|
||||
if (status) where.status = status;
|
||||
|
||||
const [items, total] = await Promise.all([
|
||||
prisma.report.findMany({
|
||||
where,
|
||||
include: { topic: true },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
skip: (Number(page) - 1) * Number(limit),
|
||||
take: Number(limit),
|
||||
}),
|
||||
prisma.report.count({ where }),
|
||||
]);
|
||||
|
||||
paginatedResponse(reply, items, total, Number(page), Number(limit));
|
||||
});
|
||||
|
||||
// 获取单个报告
|
||||
app.get('/:id', async (request, reply) => {
|
||||
const { id } = request.params as any;
|
||||
|
||||
const report = await prisma.report.findUnique({
|
||||
where: { id: parseInt(id) },
|
||||
include: {
|
||||
topic: { include: { llmConfig: true } },
|
||||
},
|
||||
});
|
||||
|
||||
if (!report) {
|
||||
throw new NotFoundError('报告不存在');
|
||||
}
|
||||
|
||||
successResponse(reply, report);
|
||||
});
|
||||
|
||||
// 删除报告
|
||||
app.delete('/:id', async (request, reply) => {
|
||||
const { id } = request.params as any;
|
||||
|
||||
const existing = await prisma.report.findUnique({
|
||||
where: { id: parseInt(id) },
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
throw new NotFoundError('报告不存在');
|
||||
}
|
||||
|
||||
await prisma.report.delete({ where: { id: parseInt(id) } });
|
||||
|
||||
successResponse(reply, null, '报告删除成功');
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import { FastifyInstance } from 'fastify';
|
||||
import prisma from '../../config/database';
|
||||
import { successResponse, paginatedResponse } from '../../utils/response';
|
||||
import { NotFoundError, BadRequestError } from '../../utils/errors';
|
||||
|
||||
export async function sourceRoutes(app: FastifyInstance): Promise<void> {
|
||||
// 获取数据源列表
|
||||
app.get('/', async (request, reply) => {
|
||||
const { page = 1, limit = 20, type } = request.query as any;
|
||||
|
||||
const where: any = {};
|
||||
if (type) where.type = type;
|
||||
|
||||
const [items, total] = await Promise.all([
|
||||
prisma.source.findMany({
|
||||
where,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
skip: (Number(page) - 1) * Number(limit),
|
||||
take: Number(limit),
|
||||
}),
|
||||
prisma.source.count({ where }),
|
||||
]);
|
||||
|
||||
paginatedResponse(reply, items, total, Number(page), Number(limit));
|
||||
});
|
||||
|
||||
// 获取单个数据源
|
||||
app.get('/:id', async (request, reply) => {
|
||||
const { id } = request.params as any;
|
||||
|
||||
const source = await prisma.source.findUnique({
|
||||
where: { id: parseInt(id) },
|
||||
include: {
|
||||
topicSources: { include: { topic: true } },
|
||||
},
|
||||
});
|
||||
|
||||
if (!source) {
|
||||
throw new NotFoundError('数据源不存在');
|
||||
}
|
||||
|
||||
successResponse(reply, source);
|
||||
});
|
||||
|
||||
// 创建数据源
|
||||
app.post('/', async (request, reply) => {
|
||||
const { name, type, config, cronExpression, enabled } = request.body as any;
|
||||
|
||||
if (!name || !type || !config || !cronExpression) {
|
||||
throw new BadRequestError('缺少必填字段');
|
||||
}
|
||||
|
||||
const source = await prisma.source.create({
|
||||
data: { name, type, config, cronExpression, enabled: enabled ?? true },
|
||||
});
|
||||
|
||||
successResponse(reply, source, '数据源创建成功', 201);
|
||||
});
|
||||
|
||||
// 更新数据源
|
||||
app.put('/:id', async (request, reply) => {
|
||||
const { id } = request.params as any;
|
||||
const { name, type, config, cronExpression, enabled } = request.body as any;
|
||||
|
||||
const existing = await prisma.source.findUnique({
|
||||
where: { id: parseInt(id) },
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
throw new NotFoundError('数据源不存在');
|
||||
}
|
||||
|
||||
// 构建更新数据对象,只包含提供的字段
|
||||
const updateData: any = {};
|
||||
if (name !== undefined) updateData.name = name;
|
||||
if (type !== undefined) updateData.type = type;
|
||||
if (config !== undefined) updateData.config = config;
|
||||
if (cronExpression !== undefined) updateData.cronExpression = cronExpression;
|
||||
if (enabled !== undefined) updateData.enabled = enabled;
|
||||
|
||||
const source = await prisma.source.update({
|
||||
where: { id: parseInt(id) },
|
||||
data: updateData,
|
||||
});
|
||||
|
||||
successResponse(reply, source, '数据源更新成功');
|
||||
});
|
||||
|
||||
// 删除数据源
|
||||
app.delete('/:id', async (request, reply) => {
|
||||
const { id } = request.params as any;
|
||||
|
||||
const existing = await prisma.source.findUnique({
|
||||
where: { id: parseInt(id) },
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
throw new NotFoundError('数据源不存在');
|
||||
}
|
||||
|
||||
await prisma.source.delete({ where: { id: parseInt(id) } });
|
||||
|
||||
successResponse(reply, null, '数据源删除成功');
|
||||
});
|
||||
|
||||
// 手动触发采集
|
||||
app.post('/:id/collect', async (request, reply) => {
|
||||
const { id } = request.params as any;
|
||||
const { CollectorService } = await import('../../services/collector.service');
|
||||
|
||||
const source = await prisma.source.findUnique({
|
||||
where: { id: parseInt(id) },
|
||||
});
|
||||
|
||||
if (!source) {
|
||||
throw new NotFoundError('数据源不存在');
|
||||
}
|
||||
|
||||
const collectorService = new CollectorService();
|
||||
collectorService.collectSource(source.id).catch((error) => {
|
||||
console.error('采集失败:', error);
|
||||
});
|
||||
|
||||
successResponse(reply, null, '采集任务已触发');
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
import { FastifyInstance } from 'fastify';
|
||||
import prisma from '../../config/database';
|
||||
import { successResponse, paginatedResponse } from '../../utils/response';
|
||||
import { NotFoundError, BadRequestError } from '../../utils/errors';
|
||||
|
||||
export async function topicRoutes(app: FastifyInstance): Promise<void> {
|
||||
// 获取主题列表
|
||||
app.get('/', async (request, reply) => {
|
||||
const { page = 1, limit = 20 } = request.query as any;
|
||||
|
||||
const [items, total] = await Promise.all([
|
||||
prisma.topic.findMany({
|
||||
include: {
|
||||
llmConfig: true,
|
||||
topicSources: { include: { source: true } },
|
||||
topicChannels: { include: { channel: true } },
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
skip: (Number(page) - 1) * Number(limit),
|
||||
take: Number(limit),
|
||||
}),
|
||||
prisma.topic.count(),
|
||||
]);
|
||||
|
||||
paginatedResponse(reply, items, total, Number(page), Number(limit));
|
||||
});
|
||||
|
||||
// 获取单个主题
|
||||
app.get('/:id', async (request, reply) => {
|
||||
const { id } = request.params as any;
|
||||
|
||||
const topic = await prisma.topic.findUnique({
|
||||
where: { id: parseInt(id) },
|
||||
include: {
|
||||
llmConfig: true,
|
||||
topicSources: { include: { source: true } },
|
||||
topicChannels: { include: { channel: true } },
|
||||
},
|
||||
});
|
||||
|
||||
if (!topic) {
|
||||
throw new NotFoundError('主题不存在');
|
||||
}
|
||||
|
||||
successResponse(reply, topic);
|
||||
});
|
||||
|
||||
// 创建主题
|
||||
app.post('/', async (request, reply) => {
|
||||
const {
|
||||
name,
|
||||
description,
|
||||
processMode,
|
||||
llmConfigId,
|
||||
scheduleConfig,
|
||||
sourceIds,
|
||||
channelIds,
|
||||
enabled,
|
||||
} = request.body as any;
|
||||
|
||||
if (!name || !processMode || !scheduleConfig) {
|
||||
throw new BadRequestError('缺少必填字段');
|
||||
}
|
||||
|
||||
const topic = await prisma.topic.create({
|
||||
data: {
|
||||
name,
|
||||
description,
|
||||
processMode,
|
||||
llmConfigId,
|
||||
scheduleConfig,
|
||||
enabled: enabled ?? true,
|
||||
},
|
||||
});
|
||||
|
||||
// 关联数据源
|
||||
if (sourceIds?.length > 0) {
|
||||
await prisma.topicSource.createMany({
|
||||
data: sourceIds.map((sourceId: number) => ({
|
||||
topicId: topic.id,
|
||||
sourceId,
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
// 关联推送渠道
|
||||
if (channelIds?.length > 0) {
|
||||
await prisma.topicChannel.createMany({
|
||||
data: channelIds.map((channelId: number) => ({
|
||||
topicId: topic.id,
|
||||
channelId,
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
successResponse(reply, topic, '主题创建成功', 201);
|
||||
});
|
||||
|
||||
// 更新主题
|
||||
app.put('/:id', async (request, reply) => {
|
||||
const { id } = request.params as any;
|
||||
const {
|
||||
name,
|
||||
description,
|
||||
processMode,
|
||||
llmConfigId,
|
||||
scheduleConfig,
|
||||
sourceIds,
|
||||
channelIds,
|
||||
enabled,
|
||||
} = request.body as any;
|
||||
|
||||
const existing = await prisma.topic.findUnique({
|
||||
where: { id: parseInt(id) },
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
throw new NotFoundError('主题不存在');
|
||||
}
|
||||
|
||||
// 构建更新数据对象,只包含提供的字段
|
||||
const updateData: any = {};
|
||||
if (name !== undefined) updateData.name = name;
|
||||
if (description !== undefined) updateData.description = description;
|
||||
if (processMode !== undefined) updateData.processMode = processMode;
|
||||
if (llmConfigId !== undefined) updateData.llmConfigId = llmConfigId;
|
||||
if (scheduleConfig !== undefined) updateData.scheduleConfig = scheduleConfig;
|
||||
if (enabled !== undefined) updateData.enabled = enabled;
|
||||
|
||||
const topic = await prisma.topic.update({
|
||||
where: { id: parseInt(id) },
|
||||
data: updateData,
|
||||
});
|
||||
|
||||
// 更新数据源关联
|
||||
if (sourceIds !== undefined) {
|
||||
await prisma.topicSource.deleteMany({ where: { topicId: topic.id } });
|
||||
if (sourceIds.length > 0) {
|
||||
await prisma.topicSource.createMany({
|
||||
data: sourceIds.map((sourceId: number) => ({
|
||||
topicId: topic.id,
|
||||
sourceId,
|
||||
})),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 更新推送渠道关联
|
||||
if (channelIds !== undefined) {
|
||||
await prisma.topicChannel.deleteMany({ where: { topicId: topic.id } });
|
||||
if (channelIds.length > 0) {
|
||||
await prisma.topicChannel.createMany({
|
||||
data: channelIds.map((channelId: number) => ({
|
||||
topicId: topic.id,
|
||||
channelId,
|
||||
})),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
successResponse(reply, topic, '主题更新成功');
|
||||
});
|
||||
|
||||
// 删除主题
|
||||
app.delete('/:id', async (request, reply) => {
|
||||
const { id } = request.params as any;
|
||||
|
||||
const existing = await prisma.topic.findUnique({
|
||||
where: { id: parseInt(id) },
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
throw new NotFoundError('主题不存在');
|
||||
}
|
||||
|
||||
await prisma.topic.delete({ where: { id: parseInt(id) } });
|
||||
|
||||
successResponse(reply, null, '主题删除成功');
|
||||
});
|
||||
|
||||
// 手动生成报告
|
||||
app.post('/:id/generate-report', async (request, reply) => {
|
||||
const { id } = request.params as any;
|
||||
const { ReportService } = await import('../../services/report.service');
|
||||
const { DistributorService } = await import('../../services/distributor.service');
|
||||
|
||||
const topic = await prisma.topic.findUnique({
|
||||
where: { id: parseInt(id) },
|
||||
});
|
||||
|
||||
if (!topic) {
|
||||
throw new NotFoundError('主题不存在');
|
||||
}
|
||||
|
||||
const reportService = new ReportService();
|
||||
const distributorService = new DistributorService();
|
||||
|
||||
reportService.generateReportForTopic(topic.id).then(async (reportId) => {
|
||||
await distributorService.distributeReportToAllChannels(reportId);
|
||||
}).catch((error) => {
|
||||
console.error('报告生成失败:', error);
|
||||
});
|
||||
|
||||
successResponse(reply, null, '报告生成任务已触发');
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,387 @@
|
||||
import { beforeAll, afterAll, beforeEach, describe, it, expect } from 'vitest';
|
||||
import { createTestApp } from './helpers/app';
|
||||
import { cleanupDatabase, prisma } from './setup';
|
||||
|
||||
describe('资讯 API', () => {
|
||||
let app: Awaited<ReturnType<typeof createTestApp>>;
|
||||
|
||||
beforeAll(async () => {
|
||||
app = await createTestApp();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await cleanupDatabase();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
await cleanupDatabase();
|
||||
});
|
||||
|
||||
describe('GET /api/v1/articles', () => {
|
||||
it('应返回资讯列表', async () => {
|
||||
const source = await prisma.source.create({
|
||||
data: {
|
||||
name: '测试源',
|
||||
type: 'rss',
|
||||
config: { url: 'https://example.com/rss' },
|
||||
cronExpression: '0 * * * *',
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.article.createMany({
|
||||
data: [
|
||||
{
|
||||
sourceId: source.id,
|
||||
collectedAt: new Date('2024-01-01T00:00:00Z'),
|
||||
title: '文章 1',
|
||||
url: 'https://example.com/1',
|
||||
content: '内容 1',
|
||||
publishedAt: new Date('2024-01-01'),
|
||||
collectedAt: new Date('2024-01-01T00:00:00Z'),
|
||||
},
|
||||
{
|
||||
sourceId: source.id,
|
||||
collectedAt: new Date('2024-01-01T00:00:00Z'),
|
||||
title: '文章 2',
|
||||
url: 'https://example.com/2',
|
||||
content: '内容 2',
|
||||
publishedAt: new Date('2024-01-02'),
|
||||
collectedAt: new Date('2024-01-02T00:00:00Z'),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/articles',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data).toHaveLength(2);
|
||||
expect(body.pagination.total).toBe(2);
|
||||
expect(body.data[0].source).toBeDefined();
|
||||
});
|
||||
|
||||
it('应支持按数据源筛选', async () => {
|
||||
const source1 = await prisma.source.create({
|
||||
data: {
|
||||
name: '源 1',
|
||||
type: 'rss',
|
||||
config: { url: 'https://example.com/rss1' },
|
||||
cronExpression: '0 * * * *',
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const source2 = await prisma.source.create({
|
||||
data: {
|
||||
name: '源 2',
|
||||
type: 'rss',
|
||||
config: { url: 'https://example.com/rss2' },
|
||||
cronExpression: '0 * * * *',
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.article.create({
|
||||
data: {
|
||||
sourceId: source1.id,
|
||||
title: '来自源 1',
|
||||
url: 'https://example.com/1',
|
||||
content: '内容',
|
||||
collectedAt: new Date('2024-01-01T00:00:00Z'),
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.article.create({
|
||||
data: {
|
||||
sourceId: source2.id,
|
||||
title: '来自源 2',
|
||||
url: 'https://example.com/2',
|
||||
content: '内容',
|
||||
collectedAt: new Date('2024-01-01T00:00:00Z'),
|
||||
},
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/v1/articles?sourceId=${source1.id}`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data).toHaveLength(1);
|
||||
expect(body.data[0].sourceId).toBe(source1.id);
|
||||
});
|
||||
|
||||
it('应支持按主题筛选(返回主题关联的所有数据源的文章)', async () => {
|
||||
const source1 = await prisma.source.create({
|
||||
data: {
|
||||
name: '源 1',
|
||||
type: 'rss',
|
||||
config: { url: 'https://example.com/rss1' },
|
||||
cronExpression: '0 * * * *',
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const source2 = await prisma.source.create({
|
||||
data: {
|
||||
name: '源 2',
|
||||
type: 'rss',
|
||||
config: { url: 'https://example.com/rss2' },
|
||||
cronExpression: '0 * * * *',
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const source3 = await prisma.source.create({
|
||||
data: {
|
||||
name: '源 3',
|
||||
type: 'rss',
|
||||
config: { url: 'https://example.com/rss3' },
|
||||
cronExpression: '0 * * * *',
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const topic = await prisma.topic.create({
|
||||
data: {
|
||||
name: 'AI 资讯',
|
||||
processMode: 'summary',
|
||||
scheduleConfig: { cron: '0 0 * * 0' },
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
// 关联源 1 和源 2 到主题
|
||||
await prisma.topicSource.createMany({
|
||||
data: [
|
||||
{ topicId: topic.id, sourceId: source1.id },
|
||||
{ topicId: topic.id, sourceId: source2.id },
|
||||
],
|
||||
});
|
||||
|
||||
// 创建文章
|
||||
await prisma.article.create({
|
||||
data: {
|
||||
sourceId: source1.id,
|
||||
title: '文章 1',
|
||||
url: 'https://example.com/1',
|
||||
content: '内容',
|
||||
collectedAt: new Date('2024-01-01T00:00:00Z'),
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.article.create({
|
||||
data: {
|
||||
sourceId: source2.id,
|
||||
title: '文章 2',
|
||||
url: 'https://example.com/2',
|
||||
content: '内容',
|
||||
collectedAt: new Date('2024-01-01T00:00:00Z'),
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.article.create({
|
||||
data: {
|
||||
sourceId: source3.id,
|
||||
title: '文章 3',
|
||||
url: 'https://example.com/3',
|
||||
content: '内容',
|
||||
collectedAt: new Date('2024-01-01T00:00:00Z'),
|
||||
},
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/v1/articles?topicId=${topic.id}`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
// 只返回源 1 和源 2 的文章
|
||||
expect(body.data).toHaveLength(2);
|
||||
const sourceIds = body.data.map((item: any) => item.sourceId);
|
||||
expect(sourceIds).toContain(source1.id);
|
||||
expect(sourceIds).toContain(source2.id);
|
||||
expect(sourceIds).not.toContain(source3.id);
|
||||
});
|
||||
|
||||
it('应支持按日期范围筛选', async () => {
|
||||
const source = await prisma.source.create({
|
||||
data: {
|
||||
name: '测试源',
|
||||
type: 'rss',
|
||||
config: { url: 'https://example.com/rss' },
|
||||
cronExpression: '0 * * * *',
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.article.create({
|
||||
data: {
|
||||
sourceId: source.id,
|
||||
collectedAt: new Date('2024-01-01T00:00:00Z'),
|
||||
title: '旧文章',
|
||||
url: 'https://example.com/old',
|
||||
content: '内容',
|
||||
publishedAt: new Date('2024-01-01'),
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.article.create({
|
||||
data: {
|
||||
sourceId: source.id,
|
||||
collectedAt: new Date('2024-01-01T00:00:00Z'),
|
||||
title: '新文章',
|
||||
url: 'https://example.com/new',
|
||||
content: '内容',
|
||||
publishedAt: new Date('2024-01-15'),
|
||||
},
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/articles?startDate=2024-01-10&endDate=2024-01-20',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data).toHaveLength(1);
|
||||
expect(body.data[0].title).toBe('新文章');
|
||||
});
|
||||
|
||||
it('应支持分页', async () => {
|
||||
const source = await prisma.source.create({
|
||||
data: {
|
||||
name: '测试源',
|
||||
type: 'rss',
|
||||
config: { url: 'https://example.com/rss' },
|
||||
cronExpression: '0 * * * *',
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const data = Array.from({ length: 25 }, (_, i) => ({
|
||||
sourceId: source.id,
|
||||
collectedAt: new Date('2024-01-01T00:00:00Z'),
|
||||
title: `文章 ${i + 1}`,
|
||||
url: `https://example.com/${i}`,
|
||||
content: '内容',
|
||||
}));
|
||||
await prisma.article.createMany({ data });
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/articles?page=2&limit=10',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data).toHaveLength(10);
|
||||
expect(body.pagination.total).toBe(25);
|
||||
expect(body.pagination.page).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/articles/:id', () => {
|
||||
it('应返回单篇资讯', async () => {
|
||||
const source = await prisma.source.create({
|
||||
data: {
|
||||
name: '测试源',
|
||||
type: 'rss',
|
||||
config: { url: 'https://example.com/rss' },
|
||||
cronExpression: '0 * * * *',
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const article = await prisma.article.create({
|
||||
data: {
|
||||
sourceId: source.id,
|
||||
collectedAt: new Date('2024-01-01T00:00:00Z'),
|
||||
title: '测试文章',
|
||||
url: 'https://example.com/test',
|
||||
content: '这是文章内容',
|
||||
summary: '摘要',
|
||||
publishedAt: new Date('2024-01-01'),
|
||||
},
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/v1/articles/${article.id}`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data.id).toBe(article.id);
|
||||
expect(body.data.title).toBe('测试文章');
|
||||
expect(body.data.source).toBeDefined();
|
||||
expect(body.data.source.name).toBe('测试源');
|
||||
});
|
||||
|
||||
it('资讯不存在时应返回 404', async () => {
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/articles/99999',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.success).toBe(false);
|
||||
expect(body.error).toContain('资讯不存在');
|
||||
});
|
||||
});
|
||||
|
||||
describe('DELETE /api/v1/articles/:id', () => {
|
||||
it('应成功删除资讯', async () => {
|
||||
const source = await prisma.source.create({
|
||||
data: {
|
||||
name: '测试源',
|
||||
type: 'rss',
|
||||
config: { url: 'https://example.com/rss' },
|
||||
cronExpression: '0 * * * *',
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const article = await prisma.article.create({
|
||||
data: {
|
||||
sourceId: source.id,
|
||||
collectedAt: new Date('2024-01-01T00:00:00Z'),
|
||||
title: '待删除文章',
|
||||
url: 'https://example.com/delete',
|
||||
content: '内容',
|
||||
},
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'DELETE',
|
||||
url: `/api/v1/articles/${article.id}`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.message).toBe('资讯删除成功');
|
||||
|
||||
const deleted = await prisma.article.findUnique({
|
||||
where: { id: article.id },
|
||||
});
|
||||
expect(deleted).toBeNull();
|
||||
});
|
||||
|
||||
it('删除不存在的资讯时应返回 404', async () => {
|
||||
const response = await app.inject({
|
||||
method: 'DELETE',
|
||||
url: '/api/v1/articles/99999',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,341 @@
|
||||
import { beforeAll, afterAll, beforeEach, describe, it, expect } from 'vitest';
|
||||
import { createTestApp } from './helpers/app';
|
||||
import { cleanupDatabase, prisma } from './setup';
|
||||
|
||||
describe('推送渠道 API', () => {
|
||||
let app: Awaited<ReturnType<typeof createTestApp>>;
|
||||
|
||||
beforeAll(async () => {
|
||||
app = await createTestApp();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await cleanupDatabase();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
await cleanupDatabase();
|
||||
});
|
||||
|
||||
describe('POST /api/v1/channels', () => {
|
||||
it('应成功创建邮件类型的推送渠道', async () => {
|
||||
const payload = {
|
||||
name: '邮件通知',
|
||||
type: 'email',
|
||||
config: {
|
||||
to: 'test@example.com',
|
||||
subject: '资讯周报',
|
||||
},
|
||||
enabled: true,
|
||||
};
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/channels',
|
||||
payload,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.message).toBe('推送渠道创建成功');
|
||||
expect(body.data.name).toBe(payload.name);
|
||||
expect(body.data.type).toBe('email');
|
||||
});
|
||||
|
||||
it('应成功创建 Slack 类型的推送渠道', async () => {
|
||||
const payload = {
|
||||
name: 'Slack 通知',
|
||||
type: 'slack',
|
||||
config: {
|
||||
webhookUrl: 'https://hooks.slack.com/services/xxx',
|
||||
},
|
||||
enabled: true,
|
||||
};
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/channels',
|
||||
payload,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data.type).toBe('slack');
|
||||
});
|
||||
|
||||
it('应成功创建钉钉类型的推送渠道', async () => {
|
||||
const payload = {
|
||||
name: '钉钉通知',
|
||||
type: 'dingtalk',
|
||||
config: {
|
||||
webhookUrl: 'https://oapi.dingtalk.com/robot/send',
|
||||
secret: 'SEC123',
|
||||
},
|
||||
enabled: true,
|
||||
};
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/channels',
|
||||
payload,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data.type).toBe('dingtalk');
|
||||
});
|
||||
|
||||
it('应成功创建企业微信类型的推送渠道', async () => {
|
||||
const payload = {
|
||||
name: '企业微信通知',
|
||||
type: 'wechat',
|
||||
config: {
|
||||
webhookUrl: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send',
|
||||
},
|
||||
enabled: true,
|
||||
};
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/channels',
|
||||
payload,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data.type).toBe('wechat');
|
||||
});
|
||||
|
||||
it('缺少必填字段时应返回 400 错误', async () => {
|
||||
const payload = {
|
||||
name: '不完整渠道',
|
||||
type: 'email',
|
||||
};
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/channels',
|
||||
payload,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.success).toBe(false);
|
||||
expect(body.error).toContain('缺少必填字段');
|
||||
});
|
||||
|
||||
it('enabled 默认值应为 true', async () => {
|
||||
const payload = {
|
||||
name: '测试渠道',
|
||||
type: 'email',
|
||||
config: { to: 'test@example.com' },
|
||||
};
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/channels',
|
||||
payload,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data.enabled).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/channels', () => {
|
||||
it('应返回推送渠道列表', async () => {
|
||||
await prisma.channel.createMany({
|
||||
data: [
|
||||
{
|
||||
name: '邮件渠道',
|
||||
type: 'email',
|
||||
config: { to: 'test@example.com' },
|
||||
enabled: true,
|
||||
},
|
||||
{
|
||||
name: 'Slack 渠道',
|
||||
type: 'slack',
|
||||
config: { webhookUrl: 'https://hooks.slack.com/xxx' },
|
||||
enabled: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/channels',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data).toHaveLength(2);
|
||||
expect(body.pagination.total).toBe(2);
|
||||
});
|
||||
|
||||
it('应支持按类型筛选', async () => {
|
||||
await prisma.channel.createMany({
|
||||
data: [
|
||||
{
|
||||
name: '邮件渠道 1',
|
||||
type: 'email',
|
||||
config: { to: 'test1@example.com' },
|
||||
enabled: true,
|
||||
},
|
||||
{
|
||||
name: 'Slack 渠道 1',
|
||||
type: 'slack',
|
||||
config: { webhookUrl: 'https://hooks.slack.com/xxx' },
|
||||
enabled: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/channels?type=email',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data).toHaveLength(1);
|
||||
expect(body.data[0].type).toBe('email');
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/channels/:id', () => {
|
||||
it('应返回单个推送渠道及其关联的主题', async () => {
|
||||
const channel = await prisma.channel.create({
|
||||
data: {
|
||||
name: '测试渠道',
|
||||
type: 'email',
|
||||
config: { to: 'test@example.com' },
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const topic = await prisma.topic.create({
|
||||
data: {
|
||||
name: '测试主题',
|
||||
processMode: 'summary',
|
||||
scheduleConfig: { cron: '0 0 * * *' },
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.topicChannel.create({
|
||||
data: {
|
||||
topicId: topic.id,
|
||||
channelId: channel.id,
|
||||
},
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/v1/channels/${channel.id}`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data.id).toBe(channel.id);
|
||||
expect(body.data.topicChannels).toHaveLength(1);
|
||||
expect(body.data.topicChannels[0].topic.name).toBe('测试主题');
|
||||
});
|
||||
|
||||
it('推送渠道不存在时应返回 404', async () => {
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/channels/99999',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.success).toBe(false);
|
||||
expect(body.error).toContain('推送渠道不存在');
|
||||
});
|
||||
});
|
||||
|
||||
describe('PUT /api/v1/channels/:id', () => {
|
||||
it('应成功更新推送渠道', async () => {
|
||||
const channel = await prisma.channel.create({
|
||||
data: {
|
||||
name: '原始渠道',
|
||||
type: 'email',
|
||||
config: { to: 'old@example.com' },
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const updateData = {
|
||||
name: '更新后渠道',
|
||||
config: { to: 'new@example.com' },
|
||||
enabled: false,
|
||||
};
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'PUT',
|
||||
url: `/api/v1/channels/${channel.id}`,
|
||||
payload: updateData,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data.name).toBe('更新后渠道');
|
||||
expect(body.data.config.to).toBe('new@example.com');
|
||||
expect(body.data.enabled).toBe(false);
|
||||
expect(body.message).toBe('推送渠道更新成功');
|
||||
});
|
||||
|
||||
it('更新不存在的推送渠道时应返回 404', async () => {
|
||||
const response = await app.inject({
|
||||
method: 'PUT',
|
||||
url: '/api/v1/channels/99999',
|
||||
payload: {
|
||||
name: '更新',
|
||||
type: 'email',
|
||||
config: { to: 'test@example.com' },
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe('DELETE /api/v1/channels/:id', () => {
|
||||
it('应成功删除推送渠道', async () => {
|
||||
const channel = await prisma.channel.create({
|
||||
data: {
|
||||
name: '待删除渠道',
|
||||
type: 'email',
|
||||
config: { to: 'test@example.com' },
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'DELETE',
|
||||
url: `/api/v1/channels/${channel.id}`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.message).toBe('推送渠道删除成功');
|
||||
|
||||
const deleted = await prisma.channel.findUnique({
|
||||
where: { id: channel.id },
|
||||
});
|
||||
expect(deleted).toBeNull();
|
||||
});
|
||||
|
||||
it('删除不存在的推送渠道时应返回 404', async () => {
|
||||
const response = await app.inject({
|
||||
method: 'DELETE',
|
||||
url: '/api/v1/channels/99999',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,363 @@
|
||||
import { beforeAll, afterAll, beforeEach, describe, it, expect } from 'vitest';
|
||||
import { createTestApp } from './helpers/app';
|
||||
import { cleanupDatabase, prisma } from './setup';
|
||||
|
||||
describe('采集日志 API', () => {
|
||||
let app: Awaited<ReturnType<typeof createTestApp>>;
|
||||
|
||||
beforeAll(async () => {
|
||||
app = await createTestApp();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await cleanupDatabase();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
await cleanupDatabase();
|
||||
});
|
||||
|
||||
describe('GET /api/v1/collection-logs', () => {
|
||||
it('应返回采集日志列表', async () => {
|
||||
const source = await prisma.source.create({
|
||||
data: {
|
||||
name: '测试源',
|
||||
type: 'rss',
|
||||
config: { url: 'https://example.com/rss' },
|
||||
cronExpression: '0 * * * *',
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.collectionLog.createMany({
|
||||
data: [
|
||||
{
|
||||
sourceId: source.id,
|
||||
status: 'success',
|
||||
articlesCount: 5,
|
||||
startedAt: new Date('2024-01-01T00:00:00Z'),
|
||||
finishedAt: new Date('2024-01-01T00:01:00Z'),
|
||||
},
|
||||
{
|
||||
sourceId: source.id,
|
||||
status: 'failed',
|
||||
errorMessage: '连接超时',
|
||||
startedAt: new Date('2024-01-02T00:00:00Z'),
|
||||
finishedAt: new Date('2024-01-02T00:01:00Z'),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/collection-logs',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data).toHaveLength(2);
|
||||
expect(body.pagination.total).toBe(2);
|
||||
expect(body.data[0].source).toBeDefined();
|
||||
});
|
||||
|
||||
it('应支持按数据源筛选', async () => {
|
||||
const source1 = await prisma.source.create({
|
||||
data: {
|
||||
name: '源 1',
|
||||
type: 'rss',
|
||||
config: { url: 'https://example.com/rss1' },
|
||||
cronExpression: '0 * * * *',
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const source2 = await prisma.source.create({
|
||||
data: {
|
||||
name: '源 2',
|
||||
type: 'rss',
|
||||
config: { url: 'https://example.com/rss2' },
|
||||
cronExpression: '0 * * * *',
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.collectionLog.create({
|
||||
data: {
|
||||
sourceId: source1.id,
|
||||
status: 'success',
|
||||
articlesCount: 10,
|
||||
startedAt: new Date('2024-01-01T00:00:00Z'),
|
||||
finishedAt: new Date('2024-01-01T00:01:00Z'),
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.collectionLog.create({
|
||||
data: {
|
||||
sourceId: source2.id,
|
||||
status: 'success',
|
||||
articlesCount: 5,
|
||||
startedAt: new Date('2024-01-01T00:00:00Z'),
|
||||
finishedAt: new Date('2024-01-01T00:01:00Z'),
|
||||
},
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/v1/collection-logs?sourceId=${source1.id}`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data).toHaveLength(1);
|
||||
expect(body.data[0].sourceId).toBe(source1.id);
|
||||
expect(body.data[0].articlesCount).toBe(10);
|
||||
});
|
||||
|
||||
it('应支持按状态筛选', async () => {
|
||||
const source = await prisma.source.create({
|
||||
data: {
|
||||
name: '测试源',
|
||||
type: 'rss',
|
||||
config: { url: 'https://example.com/rss' },
|
||||
cronExpression: '0 * * * *',
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.collectionLog.createMany({
|
||||
data: [
|
||||
{
|
||||
sourceId: source.id,
|
||||
status: 'success',
|
||||
articlesCount: 10,
|
||||
startedAt: new Date('2024-01-01T00:00:00Z'),
|
||||
finishedAt: new Date('2024-01-01T00:01:00Z'),
|
||||
},
|
||||
{
|
||||
sourceId: source.id,
|
||||
status: 'failed',
|
||||
errorMessage: '错误',
|
||||
startedAt: new Date('2024-01-02T00:00:00Z'),
|
||||
finishedAt: new Date('2024-01-02T00:01:00Z'),
|
||||
},
|
||||
{
|
||||
sourceId: source.id,
|
||||
status: 'running',
|
||||
startedAt: new Date('2024-01-03T00:00:00Z'),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/collection-logs?status=success',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data).toHaveLength(1);
|
||||
expect(body.data[0].status).toBe('success');
|
||||
});
|
||||
|
||||
it('应支持分页', async () => {
|
||||
const source = await prisma.source.create({
|
||||
data: {
|
||||
name: '测试源',
|
||||
type: 'rss',
|
||||
config: { url: 'https://example.com/rss' },
|
||||
cronExpression: '0 * * * *',
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const data = Array.from({ length: 25 }, () => ({
|
||||
sourceId: source.id,
|
||||
status: 'success' as const,
|
||||
articlesCount: 5,
|
||||
startedAt: new Date('2024-01-01T00:00:00Z'),
|
||||
finishedAt: new Date('2024-01-01T00:01:00Z'),
|
||||
}));
|
||||
await prisma.collectionLog.createMany({ data });
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/collection-logs?page=2&limit=10',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data).toHaveLength(10);
|
||||
expect(body.pagination.total).toBe(25);
|
||||
expect(body.pagination.page).toBe(2);
|
||||
});
|
||||
|
||||
it('应按创建时间倒序排列', async () => {
|
||||
const source = await prisma.source.create({
|
||||
data: {
|
||||
name: '测试源',
|
||||
type: 'rss',
|
||||
config: { url: 'https://example.com/rss' },
|
||||
cronExpression: '0 * * * *',
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const log1 = await prisma.collectionLog.create({
|
||||
data: {
|
||||
sourceId: source.id,
|
||||
status: 'success',
|
||||
articlesCount: 5,
|
||||
startedAt: new Date('2024-01-01T00:00:00Z'),
|
||||
finishedAt: new Date('2024-01-01T00:01:00Z'),
|
||||
},
|
||||
});
|
||||
|
||||
// 等待确保时间差
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
|
||||
const log2 = await prisma.collectionLog.create({
|
||||
data: {
|
||||
sourceId: source.id,
|
||||
status: 'success',
|
||||
articlesCount: 3,
|
||||
startedAt: new Date('2024-01-02T00:00:00Z'),
|
||||
finishedAt: new Date('2024-01-02T00:01:00Z'),
|
||||
},
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/collection-logs',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data[0].id).toBe(log2.id);
|
||||
expect(body.data[1].id).toBe(log1.id);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/collection-logs/stats', () => {
|
||||
it('应返回所有数据源的统计信息', async () => {
|
||||
const source1 = await prisma.source.create({
|
||||
data: {
|
||||
name: 'RSS 源 1',
|
||||
type: 'rss',
|
||||
config: { url: 'https://example.com/rss1' },
|
||||
cronExpression: '0 * * * *',
|
||||
enabled: true,
|
||||
lastCollectedAt: new Date('2024-01-15T10:00:00Z'),
|
||||
},
|
||||
});
|
||||
|
||||
const source2 = await prisma.source.create({
|
||||
data: {
|
||||
name: 'API 源 1',
|
||||
type: 'api',
|
||||
config: { url: 'https://api.example.com' },
|
||||
cronExpression: '0 * * * *',
|
||||
enabled: false,
|
||||
},
|
||||
});
|
||||
|
||||
// 为源 1 创建文章
|
||||
await prisma.article.createMany({
|
||||
data: [
|
||||
{
|
||||
sourceId: source1.id,
|
||||
title: '文章 1',
|
||||
url: 'https://example.com/1',
|
||||
content: '内容',
|
||||
collectedAt: new Date('2024-01-01T00:00:00Z'),
|
||||
},
|
||||
{
|
||||
sourceId: source1.id,
|
||||
title: '文章 2',
|
||||
url: 'https://example.com/2',
|
||||
content: '内容',
|
||||
collectedAt: new Date('2024-01-01T00:00:00Z'),
|
||||
},
|
||||
{
|
||||
sourceId: source1.id,
|
||||
title: '文章 3',
|
||||
url: 'https://example.com/3',
|
||||
content: '内容',
|
||||
collectedAt: new Date('2024-01-01T00:00:00Z'),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// 为源 1 创建采集日志
|
||||
await prisma.collectionLog.createMany({
|
||||
data: [
|
||||
{
|
||||
sourceId: source1.id,
|
||||
status: 'success',
|
||||
articlesCount: 3,
|
||||
startedAt: new Date('2024-01-15T10:00:00Z'),
|
||||
finishedAt: new Date('2024-01-15T10:01:00Z'),
|
||||
},
|
||||
{
|
||||
sourceId: source1.id,
|
||||
status: 'failed',
|
||||
errorMessage: '超时',
|
||||
startedAt: new Date('2024-01-14T10:00:00Z'),
|
||||
finishedAt: new Date('2024-01-14T10:01:00Z'),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// 为源 2 创建文章
|
||||
await prisma.article.create({
|
||||
data: {
|
||||
sourceId: source2.id,
|
||||
title: '文章 4',
|
||||
url: 'https://example.com/4',
|
||||
content: '内容',
|
||||
collectedAt: new Date('2024-01-01T00:00:00Z'),
|
||||
},
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/collection-logs/stats',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data).toHaveLength(2);
|
||||
|
||||
const stats1 = body.data.find((s: any) => s.id === source1.id);
|
||||
expect(stats1).toBeDefined();
|
||||
expect(stats1.name).toBe('RSS 源 1');
|
||||
expect(stats1.type).toBe('rss');
|
||||
expect(stats1.enabled).toBe(true);
|
||||
expect(stats1.totalArticles).toBe(3);
|
||||
expect(stats1.totalCollections).toBe(2);
|
||||
expect(stats1.lastCollectedAt).toBeDefined();
|
||||
expect(stats1.lastLog).toBeDefined();
|
||||
expect(stats1.lastLog.status).toBe('success');
|
||||
|
||||
const stats2 = body.data.find((s: any) => s.id === source2.id);
|
||||
expect(stats2).toBeDefined();
|
||||
expect(stats2.name).toBe('API 源 1');
|
||||
expect(stats2.enabled).toBe(false);
|
||||
expect(stats2.totalArticles).toBe(1);
|
||||
expect(stats2.totalCollections).toBe(0);
|
||||
expect(stats2.lastCollectedAt).toBeNull();
|
||||
expect(stats2.lastLog).toBeNull();
|
||||
});
|
||||
|
||||
it('应返回空数组当没有数据源时', async () => {
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/collection-logs/stats',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data).toEqual([]);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import { beforeAll, afterAll, describe, it, expect } from 'vitest';
|
||||
import { createTestApp } from './helpers/app';
|
||||
import { cleanupDatabase, prisma } from './setup';
|
||||
|
||||
describe('健康检查 API', () => {
|
||||
let app: Awaited<ReturnType<typeof createTestApp>>;
|
||||
|
||||
beforeAll(async () => {
|
||||
app = await createTestApp();
|
||||
await cleanupDatabase();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
await cleanupDatabase();
|
||||
});
|
||||
|
||||
describe('GET /api/v1/health', () => {
|
||||
it('应返回健康状态', async () => {
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/health',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.data.status).toBe('ok');
|
||||
expect(body.data.timestamp).toBeDefined();
|
||||
expect(body.data.version).toBe('1.0.0');
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/health/detailed', () => {
|
||||
it('应返回详细的健康状态包括数据库检查', async () => {
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/health/detailed',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.data.status).toBe('ok');
|
||||
expect(body.data.checks).toBeDefined();
|
||||
expect(body.data.checks.server).toBe('ok');
|
||||
expect(body.data.checks.database).toBe('ok');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import Fastify from 'fastify';
|
||||
import cors from '@fastify/cors';
|
||||
import { healthRoutes } from '../../src/web/routes/health';
|
||||
import { llmConfigRoutes } from '../../src/web/routes/llm-configs';
|
||||
import { sourceRoutes } from '../../src/web/routes/sources';
|
||||
import { channelRoutes } from '../../src/web/routes/channels';
|
||||
import { topicRoutes } from '../../src/web/routes/topics';
|
||||
import { reportRoutes } from '../../src/web/routes/reports';
|
||||
import { articleRoutes } from '../../src/web/routes/articles';
|
||||
import { collectionLogRoutes } from '../../src/web/routes/collection-logs';
|
||||
import { AppError } from '../../src/utils/errors';
|
||||
|
||||
/**
|
||||
* 创建用于测试的 Fastify 应用实例
|
||||
*/
|
||||
export async function createTestApp() {
|
||||
const app = Fastify({
|
||||
logger: false,
|
||||
});
|
||||
|
||||
// 注册 CORS
|
||||
await app.register(cors, {
|
||||
origin: true,
|
||||
credentials: true,
|
||||
});
|
||||
|
||||
// 简单的错误处理器(复制自 error-handler.ts)
|
||||
app.setErrorHandler(async (error, request, reply) => {
|
||||
if (error instanceof AppError) {
|
||||
return reply.status(error.statusCode).send({
|
||||
success: false,
|
||||
error: error.message,
|
||||
...(error instanceof Error && process.env.NODE_ENV === 'development' && {
|
||||
stack: error.stack,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
// 处理验证错误
|
||||
if (error.validation) {
|
||||
return reply.status(400).send({
|
||||
success: false,
|
||||
error: '请求参数验证失败',
|
||||
details: error.validation,
|
||||
});
|
||||
}
|
||||
|
||||
// 未知错误
|
||||
reply.status(500).send({
|
||||
success: false,
|
||||
error: '服务器内部错误',
|
||||
});
|
||||
});
|
||||
|
||||
// 注册路由
|
||||
await app.register(healthRoutes, { prefix: '/api/v1' });
|
||||
await app.register(llmConfigRoutes, { prefix: '/api/v1/llm-configs' });
|
||||
await app.register(sourceRoutes, { prefix: '/api/v1/sources' });
|
||||
await app.register(channelRoutes, { prefix: '/api/v1/channels' });
|
||||
await app.register(topicRoutes, { prefix: '/api/v1/topics' });
|
||||
await app.register(reportRoutes, { prefix: '/api/v1/reports' });
|
||||
await app.register(articleRoutes, { prefix: '/api/v1/articles' });
|
||||
await app.register(collectionLogRoutes, { prefix: '/api/v1/collection-logs' });
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
/**
|
||||
* 等待一段时间(用于异步操作)
|
||||
*/
|
||||
export function wait(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
import { beforeAll, afterAll, beforeEach, describe, it, expect } from 'vitest';
|
||||
import { createTestApp } from './helpers/app';
|
||||
import { cleanupDatabase, prisma } from './setup';
|
||||
|
||||
describe('LLM 配置 API', () => {
|
||||
let app: Awaited<ReturnType<typeof createTestApp>>;
|
||||
|
||||
beforeAll(async () => {
|
||||
app = await createTestApp();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await cleanupDatabase();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
await cleanupDatabase();
|
||||
});
|
||||
|
||||
describe('POST /api/v1/llm-configs', () => {
|
||||
it('应成功创建 LLM 配置', async () => {
|
||||
const payload = {
|
||||
name: 'OpenAI 测试配置',
|
||||
baseUrl: 'https://api.openai.com/v1',
|
||||
model: 'gpt-4',
|
||||
apiKey: 'sk-test123',
|
||||
enabled: true,
|
||||
};
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/llm-configs',
|
||||
payload,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.message).toBe('LLM 配置创建成功');
|
||||
expect(body.data.name).toBe(payload.name);
|
||||
expect(body.data.baseUrl).toBe(payload.baseUrl);
|
||||
expect(body.data.model).toBe(payload.model);
|
||||
expect(body.data.apiKey).toBe(payload.apiKey);
|
||||
expect(body.data.enabled).toBe(true);
|
||||
expect(body.data.id).toBeDefined();
|
||||
});
|
||||
|
||||
it('缺少必填字段时应返回 400 错误', async () => {
|
||||
const payload = {
|
||||
name: '不完整配置',
|
||||
baseUrl: 'https://api.openai.com/v1',
|
||||
};
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/llm-configs',
|
||||
payload,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.success).toBe(false);
|
||||
expect(body.error).toContain('缺少必填字段');
|
||||
});
|
||||
|
||||
it('enabled 默认值应为 true', async () => {
|
||||
const payload = {
|
||||
name: 'OpenAI 测试配置',
|
||||
baseUrl: 'https://api.openai.com/v1',
|
||||
model: 'gpt-4',
|
||||
apiKey: 'sk-test123',
|
||||
};
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/llm-configs',
|
||||
payload,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data.enabled).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/llm-configs', () => {
|
||||
it('应返回配置列表', async () => {
|
||||
// 创建测试数据
|
||||
await prisma.llmConfig.createMany({
|
||||
data: [
|
||||
{
|
||||
name: '配置 1',
|
||||
baseUrl: 'https://api.openai.com/v1',
|
||||
model: 'gpt-4',
|
||||
apiKey: 'sk-key1',
|
||||
enabled: true,
|
||||
},
|
||||
{
|
||||
name: '配置 2',
|
||||
baseUrl: 'https://api.anthropic.com/v1',
|
||||
model: 'claude-3',
|
||||
apiKey: 'sk-key2',
|
||||
enabled: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/llm-configs',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data).toHaveLength(2);
|
||||
expect(body.pagination.total).toBe(2);
|
||||
expect(body.pagination.page).toBe(1);
|
||||
expect(body.pagination.limit).toBe(20);
|
||||
});
|
||||
|
||||
it('应支持分页', async () => {
|
||||
// 创建 25 条数据
|
||||
const data = Array.from({ length: 25 }, (_, i) => ({
|
||||
name: `配置 ${i + 1}`,
|
||||
baseUrl: 'https://api.openai.com/v1',
|
||||
model: 'gpt-4',
|
||||
apiKey: `sk-key${i}`,
|
||||
enabled: true,
|
||||
}));
|
||||
await prisma.llmConfig.createMany({ data });
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/llm-configs?page=2&limit=10',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data).toHaveLength(10);
|
||||
expect(body.pagination.total).toBe(25);
|
||||
expect(body.pagination.page).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/llm-configs/:id', () => {
|
||||
it('应返回单个配置', async () => {
|
||||
const config = await prisma.llmConfig.create({
|
||||
data: {
|
||||
name: '测试配置',
|
||||
baseUrl: 'https://api.openai.com/v1',
|
||||
model: 'gpt-4',
|
||||
apiKey: 'sk-test',
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/v1/llm-configs/${config.id}`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data.id).toBe(config.id);
|
||||
expect(body.data.name).toBe('测试配置');
|
||||
});
|
||||
|
||||
it('配置不存在时应返回 404', async () => {
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/llm-configs/99999',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.success).toBe(false);
|
||||
expect(body.error).toContain('LLM 配置不存在');
|
||||
});
|
||||
});
|
||||
|
||||
describe('PUT /api/v1/llm-configs/:id', () => {
|
||||
it('应成功更新配置', async () => {
|
||||
const config = await prisma.llmConfig.create({
|
||||
data: {
|
||||
name: '原始配置',
|
||||
baseUrl: 'https://api.openai.com/v1',
|
||||
model: 'gpt-4',
|
||||
apiKey: 'sk-test',
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const updateData = {
|
||||
name: '更新后配置',
|
||||
model: 'gpt-4-turbo',
|
||||
enabled: false,
|
||||
};
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'PUT',
|
||||
url: `/api/v1/llm-configs/${config.id}`,
|
||||
payload: updateData,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data.name).toBe('更新后配置');
|
||||
expect(body.data.model).toBe('gpt-4-turbo');
|
||||
expect(body.data.enabled).toBe(false);
|
||||
expect(body.message).toBe('LLM 配置更新成功');
|
||||
});
|
||||
|
||||
it('更新不存在的配置时应返回 404', async () => {
|
||||
const response = await app.inject({
|
||||
method: 'PUT',
|
||||
url: '/api/v1/llm-configs/99999',
|
||||
payload: {
|
||||
name: '更新',
|
||||
baseUrl: 'https://api.openai.com/v1',
|
||||
model: 'gpt-4',
|
||||
apiKey: 'sk-test',
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe('DELETE /api/v1/llm-configs/:id', () => {
|
||||
it('应成功删除配置', async () => {
|
||||
const config = await prisma.llmConfig.create({
|
||||
data: {
|
||||
name: '待删除配置',
|
||||
baseUrl: 'https://api.openai.com/v1',
|
||||
model: 'gpt-4',
|
||||
apiKey: 'sk-test',
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'DELETE',
|
||||
url: `/api/v1/llm-configs/${config.id}`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.message).toBe('LLM 配置删除成功');
|
||||
|
||||
// 验证已被删除
|
||||
const deleted = await prisma.llmConfig.findUnique({
|
||||
where: { id: config.id },
|
||||
});
|
||||
expect(deleted).toBeNull();
|
||||
});
|
||||
|
||||
it('删除不存在的配置时应返回 404', async () => {
|
||||
const response = await app.inject({
|
||||
method: 'DELETE',
|
||||
url: '/api/v1/llm-configs/99999',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,307 @@
|
||||
import { beforeAll, afterAll, beforeEach, describe, it, expect } from 'vitest';
|
||||
import { createTestApp } from './helpers/app';
|
||||
import { cleanupDatabase, prisma } from './setup';
|
||||
|
||||
describe('报告 API', () => {
|
||||
let app: Awaited<ReturnType<typeof createTestApp>>;
|
||||
|
||||
beforeAll(async () => {
|
||||
app = await createTestApp();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await cleanupDatabase();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
await cleanupDatabase();
|
||||
});
|
||||
|
||||
describe('GET /api/v1/reports', () => {
|
||||
it('应返回报告列表', async () => {
|
||||
const topic = await prisma.topic.create({
|
||||
data: {
|
||||
name: 'AI 资讯',
|
||||
processMode: 'summary',
|
||||
scheduleConfig: { cron: '0 0 * * 0' },
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.report.createMany({
|
||||
data: [
|
||||
{
|
||||
title: '报告 1',
|
||||
topicId: topic.id,
|
||||
status: 'completed',
|
||||
content: '报告内容 1',
|
||||
periodStart: new Date('2024-01-01'),
|
||||
periodEnd: new Date('2024-01-07'),
|
||||
},
|
||||
{
|
||||
title: '报告 2',
|
||||
topicId: topic.id,
|
||||
status: 'pending',
|
||||
content: '',
|
||||
periodStart: new Date('2024-01-08'),
|
||||
periodEnd: new Date('2024-01-14'),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/reports',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data).toHaveLength(2);
|
||||
expect(body.pagination.total).toBe(2);
|
||||
expect(body.data[0].topic).toBeDefined();
|
||||
});
|
||||
|
||||
it('应支持按主题 ID 筛选', async () => {
|
||||
const topic1 = await prisma.topic.create({
|
||||
data: {
|
||||
name: '主题 1',
|
||||
processMode: 'summary',
|
||||
scheduleConfig: { cron: '0 0 * * 0' },
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const topic2 = await prisma.topic.create({
|
||||
data: {
|
||||
name: '主题 2',
|
||||
processMode: 'summary',
|
||||
scheduleConfig: { cron: '0 0 * * 0' },
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.report.create({
|
||||
data: {
|
||||
title: '报告 1',
|
||||
topicId: topic1.id,
|
||||
status: 'completed',
|
||||
content: '报告 1',
|
||||
periodStart: new Date('2024-01-01'),
|
||||
periodEnd: new Date('2024-01-07'),
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.report.create({
|
||||
data: {
|
||||
title: '报告 2',
|
||||
topicId: topic2.id,
|
||||
status: 'completed',
|
||||
content: '报告 2',
|
||||
periodStart: new Date('2024-01-01'),
|
||||
periodEnd: new Date('2024-01-07'),
|
||||
},
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/v1/reports?topicId=${topic1.id}`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data).toHaveLength(1);
|
||||
expect(body.data[0].topicId).toBe(topic1.id);
|
||||
});
|
||||
|
||||
it('应支持按状态筛选', async () => {
|
||||
const topic = await prisma.topic.create({
|
||||
data: {
|
||||
name: 'AI 资讯',
|
||||
processMode: 'summary',
|
||||
scheduleConfig: { cron: '0 0 * * 0' },
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.report.createMany({
|
||||
data: [
|
||||
{
|
||||
title: '完成报告',
|
||||
topicId: topic.id,
|
||||
status: 'completed',
|
||||
content: '完成',
|
||||
periodStart: new Date('2024-01-01'),
|
||||
periodEnd: new Date('2024-01-07'),
|
||||
},
|
||||
{
|
||||
title: '待处理报告',
|
||||
topicId: topic.id,
|
||||
status: 'pending',
|
||||
content: '',
|
||||
periodStart: new Date('2024-01-08'),
|
||||
periodEnd: new Date('2024-01-14'),
|
||||
},
|
||||
{
|
||||
title: '失败报告',
|
||||
topicId: topic.id,
|
||||
status: 'failed',
|
||||
errorMessage: '失败',
|
||||
content: '',
|
||||
periodStart: new Date('2024-01-15'),
|
||||
periodEnd: new Date('2024-01-21'),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/reports?status=completed',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data).toHaveLength(1);
|
||||
expect(body.data[0].status).toBe('completed');
|
||||
});
|
||||
|
||||
it('应支持分页', async () => {
|
||||
const topic = await prisma.topic.create({
|
||||
data: {
|
||||
name: 'AI 资讯',
|
||||
processMode: 'summary',
|
||||
scheduleConfig: { cron: '0 0 * * 0' },
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const data = Array.from({ length: 25 }, (_, i) => ({
|
||||
title: `报告 ${i + 1}`,
|
||||
topicId: topic.id,
|
||||
status: 'completed' as const,
|
||||
content: '报告内容',
|
||||
periodStart: new Date('2024-01-01'),
|
||||
periodEnd: new Date('2024-01-07'),
|
||||
}));
|
||||
await prisma.report.createMany({ data });
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/reports?page=2&limit=10',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data).toHaveLength(10);
|
||||
expect(body.pagination.total).toBe(25);
|
||||
expect(body.pagination.page).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/reports/:id', () => {
|
||||
it('应返回单个报告及关联的主题数据', async () => {
|
||||
const llmConfig = await prisma.llmConfig.create({
|
||||
data: {
|
||||
name: 'OpenAI',
|
||||
baseUrl: 'https://api.openai.com/v1',
|
||||
model: 'gpt-4',
|
||||
apiKey: 'sk-test',
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const topic = await prisma.topic.create({
|
||||
data: {
|
||||
name: 'AI 资讯',
|
||||
processMode: 'summary',
|
||||
scheduleConfig: { cron: '0 0 * * 0' },
|
||||
llmConfigId: llmConfig.id,
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const report = await prisma.report.create({
|
||||
data: {
|
||||
title: 'AI 资讯周报',
|
||||
topicId: topic.id,
|
||||
status: 'completed',
|
||||
content: '这是 AI 资讯周报',
|
||||
periodStart: new Date('2024-01-01'),
|
||||
periodEnd: new Date('2024-01-07'),
|
||||
},
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/v1/reports/${report.id}`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data.id).toBe(report.id);
|
||||
expect(body.data.content).toBe('这是 AI 资讯周报');
|
||||
expect(body.data.topic).toBeDefined();
|
||||
expect(body.data.topic.llmConfig).toBeDefined();
|
||||
expect(body.data.topic.llmConfig.name).toBe('OpenAI');
|
||||
});
|
||||
|
||||
it('报告不存在时应返回 404', async () => {
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/reports/99999',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.success).toBe(false);
|
||||
expect(body.error).toContain('报告不存在');
|
||||
});
|
||||
});
|
||||
|
||||
describe('DELETE /api/v1/reports/:id', () => {
|
||||
it('应成功删除报告', async () => {
|
||||
const topic = await prisma.topic.create({
|
||||
data: {
|
||||
name: 'AI 资讯',
|
||||
processMode: 'summary',
|
||||
scheduleConfig: { cron: '0 0 * * 0' },
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const report = await prisma.report.create({
|
||||
data: {
|
||||
title: '待删除报告',
|
||||
topicId: topic.id,
|
||||
status: 'completed',
|
||||
content: '报告内容',
|
||||
periodStart: new Date('2024-01-01'),
|
||||
periodEnd: new Date('2024-01-07'),
|
||||
},
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'DELETE',
|
||||
url: `/api/v1/reports/${report.id}`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.message).toBe('报告删除成功');
|
||||
|
||||
const deleted = await prisma.report.findUnique({
|
||||
where: { id: report.id },
|
||||
});
|
||||
expect(deleted).toBeNull();
|
||||
});
|
||||
|
||||
it('删除不存在的报告时应返回 404', async () => {
|
||||
const response = await app.inject({
|
||||
method: 'DELETE',
|
||||
url: '/api/v1/reports/99999',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
// 使用单独的测试数据库 URL(如果配置了)或默认数据库
|
||||
const testDatabaseUrl = process.env.TEST_DATABASE_URL || process.env.DATABASE_URL;
|
||||
|
||||
const prisma = new PrismaClient({
|
||||
datasources: {
|
||||
db: {
|
||||
url: testDatabaseUrl,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
export async function setup() {
|
||||
await prisma.$connect();
|
||||
console.log('测试数据库已连接');
|
||||
}
|
||||
|
||||
export async function teardown() {
|
||||
await prisma.$disconnect();
|
||||
console.log('测试数据库已断开');
|
||||
}
|
||||
|
||||
// 清理数据库(按依赖关系顺序删除表以避免外键约束)
|
||||
export async function cleanupDatabase() {
|
||||
// 按依赖关系顺序删除(从最底层的依赖开始)
|
||||
// 删除所有关联和日志表
|
||||
await prisma.pushLog.deleteMany({});
|
||||
await prisma.conversation.deleteMany({});
|
||||
await prisma.article.deleteMany({});
|
||||
await prisma.report.deleteMany({});
|
||||
await prisma.collectionLog.deleteMany({});
|
||||
|
||||
// 删除关联表(在删除主表之前)
|
||||
await prisma.topicSource.deleteMany({});
|
||||
await prisma.topicChannel.deleteMany({});
|
||||
|
||||
// 删除主表
|
||||
await prisma.topic.deleteMany({});
|
||||
await prisma.channel.deleteMany({});
|
||||
await prisma.source.deleteMany({});
|
||||
await prisma.llmConfig.deleteMany({});
|
||||
}
|
||||
|
||||
export { prisma };
|
||||
@@ -0,0 +1,385 @@
|
||||
import { beforeAll, afterAll, beforeEach, describe, it, expect } from 'vitest';
|
||||
import { createTestApp } from './helpers/app';
|
||||
import { cleanupDatabase, prisma } from './setup';
|
||||
|
||||
describe('数据源 API', () => {
|
||||
let app: Awaited<ReturnType<typeof createTestApp>>;
|
||||
|
||||
beforeAll(async () => {
|
||||
app = await createTestApp();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await cleanupDatabase();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
await cleanupDatabase();
|
||||
});
|
||||
|
||||
describe('POST /api/v1/sources', () => {
|
||||
it('应成功创建 RSS 类型的数据源', async () => {
|
||||
const payload = {
|
||||
name: '技术博客 RSS',
|
||||
type: 'rss',
|
||||
config: { url: 'https://example.com/rss' },
|
||||
cronExpression: '0 */6 * * *',
|
||||
enabled: true,
|
||||
};
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/sources',
|
||||
payload,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.message).toBe('数据源创建成功');
|
||||
expect(body.data.name).toBe(payload.name);
|
||||
expect(body.data.type).toBe('rss');
|
||||
});
|
||||
|
||||
it('应成功创建 API 类型的数据源', async () => {
|
||||
const payload = {
|
||||
name: '新闻 API',
|
||||
type: 'api',
|
||||
config: {
|
||||
url: 'https://api.example.com/news',
|
||||
headers: { Authorization: 'Bearer token' },
|
||||
},
|
||||
cronExpression: '0 * * * *',
|
||||
enabled: true,
|
||||
};
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/sources',
|
||||
payload,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data.type).toBe('api');
|
||||
});
|
||||
|
||||
it('应成功创建 Playwright 类型的数据源', async () => {
|
||||
const payload = {
|
||||
name: '爬虫数据源',
|
||||
type: 'playwright',
|
||||
config: {
|
||||
url: 'https://example.com',
|
||||
selectors: {
|
||||
title: '.title',
|
||||
content: '.content',
|
||||
},
|
||||
},
|
||||
cronExpression: '0 0 * * *',
|
||||
enabled: true,
|
||||
};
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/sources',
|
||||
payload,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data.type).toBe('playwright');
|
||||
});
|
||||
|
||||
it('缺少必填字段时应返回 400 错误', async () => {
|
||||
const payload = {
|
||||
name: '不完整数据源',
|
||||
type: 'rss',
|
||||
};
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/sources',
|
||||
payload,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.success).toBe(false);
|
||||
expect(body.error).toContain('缺少必填字段');
|
||||
});
|
||||
|
||||
it('enabled 默认值应为 true', async () => {
|
||||
const payload = {
|
||||
name: '测试数据源',
|
||||
type: 'rss',
|
||||
config: { url: 'https://example.com/rss' },
|
||||
cronExpression: '0 * * * *',
|
||||
};
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/sources',
|
||||
payload,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data.enabled).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/sources', () => {
|
||||
it('应返回数据源列表', async () => {
|
||||
await prisma.source.createMany({
|
||||
data: [
|
||||
{
|
||||
name: 'RSS 源 1',
|
||||
type: 'rss',
|
||||
config: { url: 'https://example.com/rss1' },
|
||||
cronExpression: '0 * * * *',
|
||||
enabled: true,
|
||||
},
|
||||
{
|
||||
name: 'API 源 1',
|
||||
type: 'api',
|
||||
config: { url: 'https://api.example.com' },
|
||||
cronExpression: '0 * * * *',
|
||||
enabled: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/sources',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data).toHaveLength(2);
|
||||
expect(body.pagination.total).toBe(2);
|
||||
});
|
||||
|
||||
it('应支持按类型筛选', async () => {
|
||||
await prisma.source.createMany({
|
||||
data: [
|
||||
{
|
||||
name: 'RSS 源 1',
|
||||
type: 'rss',
|
||||
config: { url: 'https://example.com/rss1' },
|
||||
cronExpression: '0 * * * *',
|
||||
enabled: true,
|
||||
},
|
||||
{
|
||||
name: 'API 源 1',
|
||||
type: 'api',
|
||||
config: { url: 'https://api.example.com' },
|
||||
cronExpression: '0 * * * *',
|
||||
enabled: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/sources?type=rss',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data).toHaveLength(1);
|
||||
expect(body.data[0].type).toBe('rss');
|
||||
});
|
||||
|
||||
it('应支持分页', async () => {
|
||||
const data = Array.from({ length: 25 }, (_, i) => ({
|
||||
name: `源 ${i + 1}`,
|
||||
type: 'rss' as const,
|
||||
config: { url: `https://example.com/rss${i}` },
|
||||
cronExpression: '0 * * * *',
|
||||
enabled: true,
|
||||
}));
|
||||
await prisma.source.createMany({ data });
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/sources?page=2&limit=10',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data).toHaveLength(10);
|
||||
expect(body.pagination.total).toBe(25);
|
||||
expect(body.pagination.page).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/sources/:id', () => {
|
||||
it('应返回单个数据源及其关联的主题', async () => {
|
||||
const source = await prisma.source.create({
|
||||
data: {
|
||||
name: '测试源',
|
||||
type: 'rss',
|
||||
config: { url: 'https://example.com/rss' },
|
||||
cronExpression: '0 * * * *',
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const topic = await prisma.topic.create({
|
||||
data: {
|
||||
name: '测试主题',
|
||||
processMode: 'summary',
|
||||
scheduleConfig: { cron: '0 0 * * *' },
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.topicSource.create({
|
||||
data: {
|
||||
topicId: topic.id,
|
||||
sourceId: source.id,
|
||||
},
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/v1/sources/${source.id}`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data.id).toBe(source.id);
|
||||
expect(body.data.topicSources).toHaveLength(1);
|
||||
expect(body.data.topicSources[0].topic.name).toBe('测试主题');
|
||||
});
|
||||
|
||||
it('数据源不存在时应返回 404', async () => {
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/sources/99999',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.success).toBe(false);
|
||||
expect(body.error).toContain('数据源不存在');
|
||||
});
|
||||
});
|
||||
|
||||
describe('PUT /api/v1/sources/:id', () => {
|
||||
it('应成功更新数据源', async () => {
|
||||
const source = await prisma.source.create({
|
||||
data: {
|
||||
name: '原始源',
|
||||
type: 'rss',
|
||||
config: { url: 'https://example.com/rss' },
|
||||
cronExpression: '0 * * * *',
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const updateData = {
|
||||
name: '更新后源',
|
||||
enabled: false,
|
||||
};
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'PUT',
|
||||
url: `/api/v1/sources/${source.id}`,
|
||||
payload: updateData,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data.name).toBe('更新后源');
|
||||
expect(body.data.enabled).toBe(false);
|
||||
expect(body.message).toBe('数据源更新成功');
|
||||
});
|
||||
|
||||
it('更新不存在的数据源时应返回 404', async () => {
|
||||
const response = await app.inject({
|
||||
method: 'PUT',
|
||||
url: '/api/v1/sources/99999',
|
||||
payload: {
|
||||
name: '更新',
|
||||
type: 'rss',
|
||||
config: { url: 'https://example.com' },
|
||||
cronExpression: '0 * * * *',
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe('DELETE /api/v1/sources/:id', () => {
|
||||
it('应成功删除数据源', async () => {
|
||||
const source = await prisma.source.create({
|
||||
data: {
|
||||
name: '待删除源',
|
||||
type: 'rss',
|
||||
config: { url: 'https://example.com/rss' },
|
||||
cronExpression: '0 * * * *',
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'DELETE',
|
||||
url: `/api/v1/sources/${source.id}`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.message).toBe('数据源删除成功');
|
||||
|
||||
const deleted = await prisma.source.findUnique({
|
||||
where: { id: source.id },
|
||||
});
|
||||
expect(deleted).toBeNull();
|
||||
});
|
||||
|
||||
it('删除不存在的数据源时应返回 404', async () => {
|
||||
const response = await app.inject({
|
||||
method: 'DELETE',
|
||||
url: '/api/v1/sources/99999',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/v1/sources/:id/collect', () => {
|
||||
it('应触发采集任务', async () => {
|
||||
const source = await prisma.source.create({
|
||||
data: {
|
||||
name: '测试源',
|
||||
type: 'rss',
|
||||
config: { url: 'https://example.com/rss' },
|
||||
cronExpression: '0 * * * *',
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'POST',
|
||||
url: `/api/v1/sources/${source.id}/collect`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.message).toBe('采集任务已触发');
|
||||
});
|
||||
|
||||
it('数据源不存在时应返回 404', async () => {
|
||||
const response = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/sources/99999/collect',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,440 @@
|
||||
import { beforeAll, afterAll, beforeEach, describe, it, expect } from 'vitest';
|
||||
import { createTestApp } from './helpers/app';
|
||||
import { cleanupDatabase, prisma } from './setup';
|
||||
|
||||
describe('主题 API', () => {
|
||||
let app: Awaited<ReturnType<typeof createTestApp>>;
|
||||
|
||||
beforeAll(async () => {
|
||||
app = await createTestApp();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await cleanupDatabase();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
await cleanupDatabase();
|
||||
});
|
||||
|
||||
describe('POST /api/v1/topics', () => {
|
||||
it('应成功创建主题', async () => {
|
||||
const payload = {
|
||||
name: 'AI 技术资讯',
|
||||
description: '收集 AI 相关的技术文章',
|
||||
processMode: 'summary',
|
||||
scheduleConfig: { cron: '0 0 * * 0' },
|
||||
enabled: true,
|
||||
};
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/topics',
|
||||
payload,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.message).toBe('主题创建成功');
|
||||
expect(body.data.name).toBe(payload.name);
|
||||
expect(body.data.processMode).toBe('summary');
|
||||
});
|
||||
|
||||
it('应成功创建主题并关联数据源和推送渠道', async () => {
|
||||
const source = await prisma.source.create({
|
||||
data: {
|
||||
name: '测试源',
|
||||
type: 'rss',
|
||||
config: { url: 'https://example.com/rss' },
|
||||
cronExpression: '0 * * * *',
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const channel = await prisma.channel.create({
|
||||
data: {
|
||||
name: '测试渠道',
|
||||
type: 'email',
|
||||
config: { to: 'test@example.com' },
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const payload = {
|
||||
name: '完整配置主题',
|
||||
processMode: 'summary',
|
||||
scheduleConfig: { cron: '0 0 * * 0' },
|
||||
sourceIds: [source.id],
|
||||
channelIds: [channel.id],
|
||||
};
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/topics',
|
||||
payload,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
|
||||
// 验证关联关系
|
||||
const topicSources = await prisma.topicSource.findMany({
|
||||
where: { sourceId: source.id },
|
||||
});
|
||||
expect(topicSources).toHaveLength(1);
|
||||
|
||||
const topicChannels = await prisma.topicChannel.findMany({
|
||||
where: { channelId: channel.id },
|
||||
});
|
||||
expect(topicChannels).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('应支持关联 LLM 配置', async () => {
|
||||
const llmConfig = await prisma.llmConfig.create({
|
||||
data: {
|
||||
name: 'OpenAI',
|
||||
baseUrl: 'https://api.openai.com/v1',
|
||||
model: 'gpt-4',
|
||||
apiKey: 'sk-test',
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const payload = {
|
||||
name: 'AI 资讯',
|
||||
processMode: 'summary',
|
||||
scheduleConfig: { cron: '0 0 * * 0' },
|
||||
llmConfigId: llmConfig.id,
|
||||
};
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/topics',
|
||||
payload,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(201);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data.llmConfigId).toBe(llmConfig.id);
|
||||
});
|
||||
|
||||
it('缺少必填字段时应返回 400 错误', async () => {
|
||||
const payload = {
|
||||
name: '不完整主题',
|
||||
};
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/topics',
|
||||
payload,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.success).toBe(false);
|
||||
expect(body.error).toContain('缺少必填字段');
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/topics', () => {
|
||||
it('应返回主题列表及关联数据', async () => {
|
||||
const llmConfig = await prisma.llmConfig.create({
|
||||
data: {
|
||||
name: 'OpenAI',
|
||||
baseUrl: 'https://api.openai.com/v1',
|
||||
model: 'gpt-4',
|
||||
apiKey: 'sk-test',
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const topic = await prisma.topic.create({
|
||||
data: {
|
||||
name: 'AI 资讯',
|
||||
processMode: 'summary',
|
||||
scheduleConfig: { cron: '0 0 * * 0' },
|
||||
llmConfigId: llmConfig.id,
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/topics',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data).toHaveLength(1);
|
||||
expect(body.data[0].llmConfig).toBeDefined();
|
||||
expect(body.data[0].llmConfig.name).toBe('OpenAI');
|
||||
});
|
||||
|
||||
it('应支持分页', async () => {
|
||||
const data = Array.from({ length: 25 }, (_, i) => ({
|
||||
name: `主题 ${i + 1}`,
|
||||
processMode: 'summary' as const,
|
||||
scheduleConfig: { cron: '0 0 * * 0' },
|
||||
enabled: true,
|
||||
}));
|
||||
await prisma.topic.createMany({ data });
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/topics?page=2&limit=10',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data).toHaveLength(10);
|
||||
expect(body.pagination.total).toBe(25);
|
||||
expect(body.pagination.page).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/topics/:id', () => {
|
||||
it('应返回单个主题及其完整关联数据', async () => {
|
||||
const llmConfig = await prisma.llmConfig.create({
|
||||
data: {
|
||||
name: 'OpenAI',
|
||||
baseUrl: 'https://api.openai.com/v1',
|
||||
model: 'gpt-4',
|
||||
apiKey: 'sk-test',
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const source = await prisma.source.create({
|
||||
data: {
|
||||
name: '测试源',
|
||||
type: 'rss',
|
||||
config: { url: 'https://example.com/rss' },
|
||||
cronExpression: '0 * * * *',
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const channel = await prisma.channel.create({
|
||||
data: {
|
||||
name: '测试渠道',
|
||||
type: 'email',
|
||||
config: { to: 'test@example.com' },
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const topic = await prisma.topic.create({
|
||||
data: {
|
||||
name: 'AI 资讯',
|
||||
description: 'AI 技术文章',
|
||||
processMode: 'summary',
|
||||
scheduleConfig: { cron: '0 0 * * 0' },
|
||||
llmConfigId: llmConfig.id,
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.topicSource.create({
|
||||
data: { topicId: topic.id, sourceId: source.id },
|
||||
});
|
||||
|
||||
await prisma.topicChannel.create({
|
||||
data: { topicId: topic.id, channelId: channel.id },
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/v1/topics/${topic.id}`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data.id).toBe(topic.id);
|
||||
expect(body.data.llmConfig).toBeDefined();
|
||||
expect(body.data.topicSources).toHaveLength(1);
|
||||
expect(body.data.topicSources[0].source.name).toBe('测试源');
|
||||
expect(body.data.topicChannels).toHaveLength(1);
|
||||
expect(body.data.topicChannels[0].channel.name).toBe('测试渠道');
|
||||
});
|
||||
|
||||
it('主题不存在时应返回 404', async () => {
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/topics/99999',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PUT /api/v1/topics/:id', () => {
|
||||
it('应成功更新主题', async () => {
|
||||
const topic = await prisma.topic.create({
|
||||
data: {
|
||||
name: '原始主题',
|
||||
processMode: 'summary',
|
||||
scheduleConfig: { cron: '0 0 * * 0' },
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const updateData = {
|
||||
name: '更新后主题',
|
||||
description: '新描述',
|
||||
enabled: false,
|
||||
};
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'PUT',
|
||||
url: `/api/v1/topics/${topic.id}`,
|
||||
payload: updateData,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.data.name).toBe('更新后主题');
|
||||
expect(body.data.description).toBe('新描述');
|
||||
expect(body.data.enabled).toBe(false);
|
||||
expect(body.message).toBe('主题更新成功');
|
||||
});
|
||||
|
||||
it('应更新数据源和渠道关联', async () => {
|
||||
const source1 = await prisma.source.create({
|
||||
data: {
|
||||
name: '源 1',
|
||||
type: 'rss',
|
||||
config: { url: 'https://example.com/rss1' },
|
||||
cronExpression: '0 * * * *',
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const source2 = await prisma.source.create({
|
||||
data: {
|
||||
name: '源 2',
|
||||
type: 'rss',
|
||||
config: { url: 'https://example.com/rss2' },
|
||||
cronExpression: '0 * * * *',
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const topic = await prisma.topic.create({
|
||||
data: {
|
||||
name: '测试主题',
|
||||
processMode: 'summary',
|
||||
scheduleConfig: { cron: '0 0 * * 0' },
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
// 初始关联
|
||||
await prisma.topicSource.create({
|
||||
data: { topicId: topic.id, sourceId: source1.id },
|
||||
});
|
||||
|
||||
// 更新关联
|
||||
const response = await app.inject({
|
||||
method: 'PUT',
|
||||
url: `/api/v1/topics/${topic.id}`,
|
||||
payload: {
|
||||
name: '测试主题',
|
||||
processMode: 'summary',
|
||||
scheduleConfig: { cron: '0 0 * * 0' },
|
||||
sourceIds: [source2.id],
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
|
||||
// 验证关联已更新
|
||||
const topicSources = await prisma.topicSource.findMany({
|
||||
where: { topicId: topic.id },
|
||||
});
|
||||
expect(topicSources).toHaveLength(1);
|
||||
expect(topicSources[0].sourceId).toBe(source2.id);
|
||||
});
|
||||
|
||||
it('更新不存在的主题时应返回 404', async () => {
|
||||
const response = await app.inject({
|
||||
method: 'PUT',
|
||||
url: '/api/v1/topics/99999',
|
||||
payload: {
|
||||
name: '更新',
|
||||
processMode: 'summary',
|
||||
scheduleConfig: { cron: '0 0 * * 0' },
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe('DELETE /api/v1/topics/:id', () => {
|
||||
it('应成功删除主题', async () => {
|
||||
const topic = await prisma.topic.create({
|
||||
data: {
|
||||
name: '待删除主题',
|
||||
processMode: 'summary',
|
||||
scheduleConfig: { cron: '0 0 * * 0' },
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'DELETE',
|
||||
url: `/api/v1/topics/${topic.id}`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.message).toBe('主题删除成功');
|
||||
|
||||
const deleted = await prisma.topic.findUnique({
|
||||
where: { id: topic.id },
|
||||
});
|
||||
expect(deleted).toBeNull();
|
||||
});
|
||||
|
||||
it('删除不存在的主题时应返回 404', async () => {
|
||||
const response = await app.inject({
|
||||
method: 'DELETE',
|
||||
url: '/api/v1/topics/99999',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/v1/topics/:id/generate-report', () => {
|
||||
it('应触发报告生成任务', async () => {
|
||||
const topic = await prisma.topic.create({
|
||||
data: {
|
||||
name: 'AI 资讯',
|
||||
processMode: 'summary',
|
||||
scheduleConfig: { cron: '0 0 * * 0' },
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'POST',
|
||||
url: `/api/v1/topics/${topic.id}/generate-report`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = JSON.parse(response.body);
|
||||
expect(body.message).toBe('报告生成任务已触发');
|
||||
});
|
||||
|
||||
it('主题不存在时应返回 404', async () => {
|
||||
const response = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/topics/99999/generate-report',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(404);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,7 @@
|
||||
"module": "commonjs",
|
||||
"lib": ["ES2022"],
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"rootDir": "./",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
@@ -13,6 +13,6 @@
|
||||
"moduleResolution": "node",
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"include": ["src/**/*", "tests/**/*"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
globals: true,
|
||||
environment: 'node',
|
||||
testTimeout: 30000,
|
||||
hookTimeout: 30000,
|
||||
include: ['tests/**/*.test.ts'],
|
||||
setupFiles: ['tests/setup.ts'],
|
||||
// 串行执行测试以避免数据库竞争
|
||||
fileParallelism: false,
|
||||
maxConcurrency: 1,
|
||||
alias: {
|
||||
'@': new URL('./src', import.meta.url).pathname,
|
||||
},
|
||||
},
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': '/src',
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -5,19 +5,19 @@
|
||||
## 后端任务
|
||||
|
||||
### 基础设施
|
||||
- [x] [任务 01:项目初始化](./01-project-setup.md)
|
||||
- [x] [任务 02:数据库搭建](./02-database-setup.md) - Schema 和种子数据已创建
|
||||
- [ ] [任务 03:后端核心框架](./03-backend-core.md) - 基础模块已创建,待完善中间件和路由
|
||||
- [x] [任务 01:项目初始化](./01-project-setup.md) - 已完成
|
||||
- [x] [任务 02:数据库搭建](./02-database-setup.md) - 已完成
|
||||
- [x] [任务 03:后端核心框架](./03-backend-core.md) - 已完成
|
||||
|
||||
### 核心功能
|
||||
- [ ] [任务 04:采集器实现](./04-collectors.md)
|
||||
- [ ] [任务 05:内容处理](./05-processor.md)
|
||||
- [ ] [任务 06:报告生成](./06-report-generator.md)
|
||||
- [ ] [任务 07:分发器实现](./07-distributors.md)
|
||||
- [ ] [任务 08:定时任务调度](./08-scheduler.md)
|
||||
- [x] [任务 04:采集器实现](./04-collectors.md) - 已完成
|
||||
- [x] [任务 05:内容处理](./05-processor.md) - 已完成
|
||||
- [x] [任务 06:报告生成](./06-report-generator.md) - 已完成
|
||||
- [x] [任务 07:分发器实现](./07-distributors.md) - 已完成
|
||||
- [x] [任务 08:定时任务调度](./08-scheduler.md) - 已完成
|
||||
|
||||
### API 开发
|
||||
- [ ] [任务 09:Web API 实现](./09-web-api.md)
|
||||
- [x] [任务 09:Web API 实现](./09-web-api.md) - 已完成
|
||||
|
||||
## 前端任务
|
||||
|
||||
|
||||
Reference in new issue
Block a user