实现 Web API 路由

- 添加 LLM 配置 API (llm-configs.ts)
- 添加数据源管理 API (sources.ts)
- 添加推送渠道管理 API (channels.ts)
- 添加主题管理 API (topics.ts)
- 添加报告查询 API (reports.ts)
- 添加资讯浏览 API (articles.ts)
- 添加采集日志 API (collection-logs.ts)
- 更新 app.ts 注册所有路由和调度器

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
hughhuangandClaude Opus 4.5 committed 2026-02-04 21:42:25 +08:00
1 parent 881bbb64a3
commit 51eb7d4292
8 files changed
+741

No files matched your search

+29
View File
@@ -6,6 +6,16 @@ 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 {
@@ -43,6 +53,15 @@ async function registerRoutes(): Promise<void> {
// 健康检查路由
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('路由已注册');
}
@@ -60,6 +79,10 @@ async function start(): Promise<void> {
await registerMiddleware();
await registerRoutes();
// 启动调度器
schedulerService = new SchedulerService();
await schedulerService.start();
await app.listen({
port: config.port,
host: '0.0.0.0',
@@ -87,6 +110,9 @@ process.on('unhandledRejection', (reason, promise) => {
// 优雅关闭
process.on('SIGTERM', async () => {
logger.info('SIGTERM 信号收到,正在关闭服务器...');
if (schedulerService) {
schedulerService.stop();
}
await app.close();
await disconnectDatabase();
process.exit(0);
@@ -94,6 +120,9 @@ process.on('SIGTERM', async () => {
process.on('SIGINT', async () => {
logger.info('SIGINT 信号收到,正在关闭服务器...');
if (schedulerService) {
schedulerService.stop();
}
await app.close();
await disconnectDatabase();
process.exit(0);
+92
View File
@@ -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, '资讯删除成功');
});
}
+97
View File
@@ -0,0 +1,97 @@
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 channel = await prisma.channel.update({
where: { id: parseInt(id) },
data: { name, type, config, enabled },
});
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, '推送渠道删除成功');
});
}
+55
View File
@@ -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);
});
}
+90
View File
@@ -0,0 +1,90 @@
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 config = await prisma.llmConfig.update({
where: { id: parseInt(id) },
data: { name, baseUrl, model, apiKey, enabled },
});
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 配置删除成功');
});
}
+63
View File
@@ -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, '报告删除成功');
});
}
+118
View File
@@ -0,0 +1,118 @@
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 source = await prisma.source.update({
where: { id: parseInt(id) },
data: { name, type, config, cronExpression, enabled },
});
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, '采集任务已触发');
});
}
+197
View File
@@ -0,0 +1,197 @@
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 topic = await prisma.topic.update({
where: { id: parseInt(id) },
data: { name, description, processMode, llmConfigId, scheduleConfig, enabled },
});
// 更新数据源关联
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, '报告生成任务已触发');
});
}