Files
hughhuangandClaude Sonnet 4.5 830a17bf46 初始化项目结构和基础模块
完成内容:
- 创建前后端项目目录结构
- 初始化 Node.js + TypeScript 后端项目 (Fastify)
- 初始化 Vue 3 + TypeScript 前端项目 (Vite)
- 配置 Prisma ORM 和 MySQL 数据库
- 创建数据库 Schema 和种子数据
- 实现后端基础模块 (配置、日志、错误处理、验证)
- 创建基础服务类 (BaseService)
- 配置 Git 仓库和忽略文件

技术栈:
- 后端:Fastify + Prisma + MySQL + Winston
- 前端:Vue 3 + TypeScript + Element Plus + Pinia

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-03 12:11:57 +08:00

1380 lines
31 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 任务 09:Web API 实现
## 任务概述
实现完整的 RESTful API,提供配置管理、报告查询、采集监控等功能。
## 前置条件
- 任务 01-08 已完成
- 后端核心服务已实现
## 任务目标
- 实现 LLM 配置 API
- 实现数据源管理 API
- 实现推送渠道管理 API
- 实现主题管理 API
- 实现报告查询 API
- 实现资讯浏览 API
- 实现采集监控 API
- 实现手动触发 API
## 详细步骤
### 1. 创建 LLM 配置路由
创建 `backend/src/web/routes/llm-configs.ts`:
```typescript
import type { FastifyInstance } from 'fastify'
import prisma from '../../utils/prisma'
import { ResponseHelper } from '../../utils/response'
import { NotFoundError, ValidationError } from '../../utils/errors'
export async function llmConfigRoutes(app: FastifyInstance) {
// 获取 LLM 配置列表
app.get('/', async (request) => {
const { page = 1, limit = 20 } = request.query as any
const [items, total] = await Promise.all([
prisma.llmConfig.findMany({
orderBy: { createdAt: 'desc' },
skip: (page - 1) * limit,
take: limit,
}),
prisma.llmConfig.count(),
])
return ResponseHelper.success({
items,
total,
page,
limit,
totalPages: Math.ceil(total / limit),
})
})
// 获取单个 LLM 配置
app.get('/:id', async (request) => {
const { id } = request.params as any
const config = await prisma.llmConfig.findUnique({
where: { id: parseInt(id) },
})
if (!config) {
throw new NotFoundError('LLM Config')
}
return ResponseHelper.success(config)
})
// 创建 LLM 配置
app.post('/', async (request) => {
const { name, baseUrl, model, apiKey, enabled } = request.body as any
if (!name || !baseUrl || !model || !apiKey) {
throw new ValidationError('Missing required fields')
}
const config = await prisma.llmConfig.create({
data: {
name,
baseUrl,
model,
apiKey,
enabled: enabled ?? true,
},
})
return ResponseHelper.success(config, 'LLM 配置创建成功')
})
// 更新 LLM 配置
app.put('/:id', async (request) => {
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 Config')
}
const config = await prisma.llmConfig.update({
where: { id: parseInt(id) },
data: {
name,
baseUrl,
model,
apiKey,
enabled,
},
})
return ResponseHelper.success(config, 'LLM 配置更新成功')
})
// 删除 LLM 配置
app.delete('/:id', async (request) => {
const { id } = request.params as any
const existing = await prisma.llmConfig.findUnique({
where: { id: parseInt(id) },
})
if (!existing) {
throw new NotFoundError('LLM Config')
}
await prisma.llmConfig.delete({
where: { id: parseInt(id) },
})
return ResponseHelper.success(null, 'LLM 配置删除成功')
})
}
```
### 2. 创建数据源路由
创建 `backend/src/web/routes/sources.ts`:
```typescript
import type { FastifyInstance } from 'fastify'
import prisma from '../../utils/prisma'
import { ResponseHelper } from '../../utils/response'
import { NotFoundError, ValidationError } from '../../utils/errors'
import { getScheduler } from '../../app'
export async function sourceRoutes(app: FastifyInstance) {
// 获取数据源列表
app.get('/', async (request) => {
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: (page - 1) * limit,
take: limit,
}),
prisma.source.count({ where }),
])
return ResponseHelper.success({
items,
total,
page,
limit,
totalPages: Math.ceil(total / limit),
})
})
// 获取单个数据源
app.get('/:id', async (request) => {
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('Source')
}
return ResponseHelper.success(source)
})
// 创建数据源
app.post('/', async (request) => {
const { name, type, config, cronExpression, enabled } = request.body as any
if (!name || !type || !config || !cronExpression) {
throw new ValidationError('Missing required fields')
}
const source = await prisma.source.create({
data: {
name,
type,
config,
cronExpression,
enabled: enabled ?? true,
},
})
// 如果启用,添加到调度器
if (source.enabled) {
const scheduler = getScheduler()
if (scheduler) {
scheduler.scheduleCollectionTask(source.id, source.cronExpression)
}
}
return ResponseHelper.success(source, '数据源创建成功')
})
// 更新数据源
app.put('/:id', async (request) => {
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('Source')
}
const source = await prisma.source.update({
where: { id: parseInt(id) },
data: {
name,
type,
config,
cronExpression,
enabled,
},
})
// 更新调度器
const scheduler = getScheduler()
if (scheduler) {
if (source.enabled) {
scheduler.scheduleCollectionTask(source.id, source.cronExpression)
} else {
scheduler.unscheduleTask(`collection-${source.id}`)
}
}
return ResponseHelper.success(source, '数据源更新成功')
})
// 删除数据源
app.delete('/:id', async (request) => {
const { id } = request.params as any
const existing = await prisma.source.findUnique({
where: { id: parseInt(id) },
})
if (!existing) {
throw new NotFoundError('Source')
}
// 从调度器移除
const scheduler = getScheduler()
if (scheduler) {
scheduler.unscheduleTask(`collection-${existing.id}`)
}
await prisma.source.delete({
where: { id: parseInt(id) },
})
return ResponseHelper.success(null, '数据源删除成功')
})
// 手动触发采集
app.post('/:id/collect', async (request) => {
const { id } = request.params as any
const source = await prisma.source.findUnique({
where: { id: parseInt(id) },
})
if (!source) {
throw new NotFoundError('Source')
}
const scheduler = getScheduler()
if (!scheduler) {
throw new Error('Scheduler not available')
}
// 异步执行采集
scheduler.triggerCollection(source.id).catch((error) => {
console.error('Collection failed:', error)
})
return ResponseHelper.success(null, '采集任务已触发')
})
}
```
### 3. 创建推送渠道路由
创建 `backend/src/web/routes/channels.ts`:
```typescript
import type { FastifyInstance } from 'fastify'
import prisma from '../../utils/prisma'
import { ResponseHelper } from '../../utils/response'
import { NotFoundError, ValidationError } from '../../utils/errors'
export async function channelRoutes(app: FastifyInstance) {
// 获取推送渠道列表
app.get('/', async (request) => {
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: (page - 1) * limit,
take: limit,
}),
prisma.channel.count({ where }),
])
return ResponseHelper.success({
items,
total,
page,
limit,
totalPages: Math.ceil(total / limit),
})
})
// 获取单个推送渠道
app.get('/:id', async (request) => {
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('Channel')
}
return ResponseHelper.success(channel)
})
// 创建推送渠道
app.post('/', async (request) => {
const { name, type, config, enabled } = request.body as any
if (!name || !type || !config) {
throw new ValidationError('Missing required fields')
}
const channel = await prisma.channel.create({
data: {
name,
type,
config,
enabled: enabled ?? true,
},
})
return ResponseHelper.success(channel, '推送渠道创建成功')
})
// 更新推送渠道
app.put('/:id', async (request) => {
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('Channel')
}
const channel = await prisma.channel.update({
where: { id: parseInt(id) },
data: {
name,
type,
config,
enabled,
},
})
return ResponseHelper.success(channel, '推送渠道更新成功')
})
// 删除推送渠道
app.delete('/:id', async (request) => {
const { id } = request.params as any
const existing = await prisma.channel.findUnique({
where: { id: parseInt(id) },
})
if (!existing) {
throw new NotFoundError('Channel')
}
await prisma.channel.delete({
where: { id: parseInt(id) },
})
return ResponseHelper.success(null, '推送渠道删除成功')
})
}
```
### 4. 创建主题路由
创建 `backend/src/web/routes/topics.ts`:
```typescript
import type { FastifyInstance } from 'fastify'
import prisma from '../../utils/prisma'
import { ResponseHelper } from '../../utils/response'
import { NotFoundError, ValidationError } from '../../utils/errors'
import { getScheduler } from '../../app'
export async function topicRoutes(app: FastifyInstance) {
// 获取主题列表
app.get('/', async (request) => {
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: (page - 1) * limit,
take: limit,
}),
prisma.topic.count(),
])
return ResponseHelper.success({
items,
total,
page,
limit,
totalPages: Math.ceil(total / limit),
})
})
// 获取单个主题
app.get('/:id', async (request) => {
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('Topic')
}
return ResponseHelper.success(topic)
})
// 创建主题
app.post('/', async (request) => {
const {
name,
description,
processMode,
llmConfigId,
scheduleConfig,
sourceIds,
channelIds,
enabled,
} = request.body as any
if (!name || !processMode || !scheduleConfig) {
throw new ValidationError('Missing required fields')
}
const topic = await prisma.topic.create({
data: {
name,
description,
processMode,
llmConfigId,
scheduleConfig,
enabled: enabled ?? true,
},
})
// 关联数据源
if (sourceIds && sourceIds.length > 0) {
await prisma.topicSource.createMany({
data: sourceIds.map((sourceId: number) => ({
topicId: topic.id,
sourceId,
})),
})
}
// 关联推送渠道
if (channelIds && channelIds.length > 0) {
await prisma.topicChannel.createMany({
data: channelIds.map((channelId: number) => ({
topicId: topic.id,
channelId,
})),
})
}
// 添加到调度器
if (topic.enabled && scheduleConfig.cron) {
const scheduler = getScheduler()
if (scheduler) {
scheduler.scheduleReportTask(topic.id, scheduleConfig.cron)
}
}
return ResponseHelper.success(topic, '主题创建成功')
})
// 更新主题
app.put('/:id', async (request) => {
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('Topic')
}
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,
})),
})
}
}
// 更新调度器
const scheduler = getScheduler()
if (scheduler) {
if (topic.enabled && scheduleConfig?.cron) {
scheduler.scheduleReportTask(topic.id, scheduleConfig.cron)
} else {
scheduler.unscheduleTask(`report-${topic.id}`)
}
}
return ResponseHelper.success(topic, '主题更新成功')
})
// 删除主题
app.delete('/:id', async (request) => {
const { id } = request.params as any
const existing = await prisma.topic.findUnique({
where: { id: parseInt(id) },
})
if (!existing) {
throw new NotFoundError('Topic')
}
// 从调度器移除
const scheduler = getScheduler()
if (scheduler) {
scheduler.unscheduleTask(`report-${existing.id}`)
}
await prisma.topic.delete({
where: { id: parseInt(id) },
})
return ResponseHelper.success(null, '主题删除成功')
})
// 手动生成报告
app.post('/:id/generate-report', async (request) => {
const { id } = request.params as any
const topic = await prisma.topic.findUnique({
where: { id: parseInt(id) },
})
if (!topic) {
throw new NotFoundError('Topic')
}
const scheduler = getScheduler()
if (!scheduler) {
throw new Error('Scheduler not available')
}
// 异步执行报告生成
scheduler.triggerReport(topic.id).catch((error) => {
console.error('Report generation failed:', error)
})
return ResponseHelper.success(null, '报告生成任务已触发')
})
}
```
### 5. 创建报告路由
创建 `backend/src/web/routes/reports.ts`:
```typescript
import type { FastifyInstance } from 'fastify'
import prisma from '../../utils/prisma'
import { ResponseHelper } from '../../utils/response'
import { NotFoundError } from '../../utils/errors'
export async function reportRoutes(app: FastifyInstance) {
// 获取报告列表
app.get('/', async (request) => {
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: (page - 1) * limit,
take: limit,
}),
prisma.report.count({ where }),
])
return ResponseHelper.success({
items,
total,
page,
limit,
totalPages: Math.ceil(total / limit),
})
})
// 获取单个报告
app.get('/:id', async (request) => {
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('Report')
}
return ResponseHelper.success(report)
})
// 删除报告
app.delete('/:id', async (request) => {
const { id } = request.params as any
const existing = await prisma.report.findUnique({
where: { id: parseInt(id) },
})
if (!existing) {
throw new NotFoundError('Report')
}
await prisma.report.delete({
where: { id: parseInt(id) },
})
return ResponseHelper.success(null, '报告删除成功')
})
}
```
### 6. 创建资讯路由
创建 `backend/src/web/routes/articles.ts`:
```typescript
import type { FastifyInstance } from 'fastify'
import prisma from '../../utils/prisma'
import { ResponseHelper } from '../../utils/response'
import { NotFoundError } from '../../utils/errors'
export async function articleRoutes(app: FastifyInstance) {
// 获取资讯列表
app.get('/', async (request) => {
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: (page - 1) * limit,
take: limit,
}),
prisma.article.count({ where }),
])
return ResponseHelper.success({
items,
total,
page,
limit,
totalPages: Math.ceil(total / limit),
})
})
// 获取单个资讯
app.get('/:id', async (request) => {
const { id } = request.params as any
const article = await prisma.article.findUnique({
where: { id: parseInt(id) },
include: {
source: true,
},
})
if (!article) {
throw new NotFoundError('Article')
}
return ResponseHelper.success(article)
})
// 删除资讯
app.delete('/:id', async (request) => {
const { id } = request.params as any
const existing = await prisma.article.findUnique({
where: { id: parseInt(id) },
})
if (!existing) {
throw new NotFoundError('Article')
}
await prisma.article.delete({
where: { id: parseInt(id) },
})
return ResponseHelper.success(null, '资讯删除成功')
})
}
```
### 7. 创建采集日志路由
创建 `backend/src/web/routes/collection-logs.ts`:
```typescript
import type { FastifyInstance } from 'fastify'
import prisma from '../../utils/prisma'
import { ResponseHelper } from '../../utils/response'
export async function collectionLogRoutes(app: FastifyInstance) {
// 获取采集日志列表
app.get('/', async (request) => {
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: (page - 1) * limit,
take: limit,
}),
prisma.collectionLog.count({ where }),
])
return ResponseHelper.success({
items,
total,
page,
limit,
totalPages: Math.ceil(total / limit),
})
})
// 获取数据源统计
app.get('/stats', async () => {
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,
}))
return ResponseHelper.success(stats)
})
}
```
### 8. 更新应用入口,注册所有路由
更新 `backend/src/app.ts`:
```typescript
import Fastify from 'fastify'
import cors from '@fastify/cors'
import { config } from './config'
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
export async function createApp() {
const app = Fastify({
logger: false,
})
// 注册 CORS
await app.register(cors, {
origin: config.cors.origin,
credentials: config.cors.credentials,
})
// 注册中间件
app.addHook('onRequest', requestLogger)
// 注册错误处理
app.setErrorHandler(errorHandler)
// 注册路由
await app.register(healthRoutes, { prefix: '/api' })
await app.register(llmConfigRoutes, { prefix: '/api/llm-configs' })
await app.register(sourceRoutes, { prefix: '/api/sources' })
await app.register(channelRoutes, { prefix: '/api/channels' })
await app.register(topicRoutes, { prefix: '/api/topics' })
await app.register(reportRoutes, { prefix: '/api/reports' })
await app.register(articleRoutes, { prefix: '/api/articles' })
await app.register(collectionLogRoutes, { prefix: '/api/collection-logs' })
// 启动调度器
schedulerService = new SchedulerService()
await schedulerService.start()
// 优雅关闭
app.addHook('onClose', async () => {
logger.info('应用关闭中...')
if (schedulerService) {
schedulerService.stop()
}
})
return app
}
export async function startServer() {
try {
const app = await createApp()
await app.listen({
port: config.app.port,
host: config.app.host,
})
logger.info(`Server started on http://${config.app.host}:${config.app.port}`)
logger.info(`Environment: ${config.app.env}`)
// 处理进程信号
const signals = ['SIGINT', 'SIGTERM']
signals.forEach((signal) => {
process.on(signal, async () => {
logger.info(`收到 ${signal} 信号,准备关闭...`)
await app.close()
process.exit(0)
})
})
} catch (error) {
logger.error('Failed to start server', error)
process.exit(1)
}
}
// 如果直接运行此文件,则启动服务器
if (require.main === module) {
startServer()
}
// 导出调度器实例供其他模块使用
export function getScheduler(): SchedulerService | null {
return schedulerService
}
```
### 9. 创建 API 测试文件
创建 `backend/test-api.http`:
```http
### 健康检查
GET http://localhost:3000/api/health
### ========== LLM 配置 ==========
### 获取 LLM 配置列表
GET http://localhost:3000/api/llm-configs
### 获取单个 LLM 配置
GET http://localhost:3000/api/llm-configs/1
### 创建 LLM 配置
POST http://localhost:3000/api/llm-configs
Content-Type: application/json
{
"name": "测试 LLM",
"baseUrl": "https://api.openai.com/v1",
"model": "gpt-4o-mini",
"apiKey": "sk-xxx",
"enabled": true
}
### 更新 LLM 配置
PUT http://localhost:3000/api/llm-configs/1
Content-Type: application/json
{
"name": "更新后的 LLM",
"enabled": false
}
### 删除 LLM 配置
DELETE http://localhost:3000/api/llm-configs/1
### ========== 数据源 ==========
### 获取数据源列表
GET http://localhost:3000/api/sources
### 获取单个数据源
GET http://localhost:3000/api/sources/1
### 创建数据源
POST http://localhost:3000/api/sources
Content-Type: application/json
{
"name": "测试数据源",
"type": "api",
"config": {
"url": "https://api.example.com/news",
"method": "GET",
"mapping": {
"title": "title",
"url": "link"
}
},
"cronExpression": "0 */6 * * *",
"enabled": true
}
### 手动触发采集
POST http://localhost:3000/api/sources/1/collect
### ========== 推送渠道 ==========
### 获取推送渠道列表
GET http://localhost:3000/api/channels
### 创建推送渠道
POST http://localhost:3000/api/channels
Content-Type: application/json
{
"name": "测试邮件",
"type": "email",
"config": {
"smtp": {
"host": "smtp.example.com",
"port": 465,
"secure": true,
"auth": {
"user": "user@example.com",
"pass": "password"
}
},
"from": "News <noreply@example.com>",
"to": ["user@example.com"]
},
"enabled": true
}
### ========== 主题 ==========
### 获取主题列表
GET http://localhost:3000/api/topics
### 获取单个主题
GET http://localhost:3000/api/topics/1
### 创建主题
POST http://localhost:3000/api/topics
Content-Type: application/json
{
"name": "测试主题",
"description": "这是一个测试主题",
"processMode": "summary",
"llmConfigId": 1,
"scheduleConfig": {
"cron": "0 9 * * *",
"timezone": "Asia/Shanghai",
"period": "daily",
"lookback": 24
},
"sourceIds": [1],
"channelIds": [1],
"enabled": true
}
### 手动生成报告
POST http://localhost:3000/api/topics/1/generate-report
### ========== 报告 ==========
### 获取报告列表
GET http://localhost:3000/api/reports
### 按主题筛选报告
GET http://localhost:3000/api/reports?topicId=1
### 按状态筛选报告
GET http://localhost:3000/api/reports?status=completed
### 获取单个报告
GET http://localhost:3000/api/reports/1
### ========== 资讯 ==========
### 获取资讯列表
GET http://localhost:3000/api/articles
### 按数据源筛选资讯
GET http://localhost:3000/api/articles?sourceId=1
### 按主题筛选资讯
GET http://localhost:3000/api/articles?topicId=1
### 按时间范围筛选资讯
GET http://localhost:3000/api/articles?startDate=2024-01-01&endDate=2024-01-31
### 获取单个资讯
GET http://localhost:3000/api/articles/1
### ========== 采集日志 ==========
### 获取采集日志列表
GET http://localhost:3000/api/collection-logs
### 按数据源筛选日志
GET http://localhost:3000/api/collection-logs?sourceId=1
### 获取数据源统计
GET http://localhost:3000/api/collection-logs/stats
```
## 验证步骤
### 1. 启动服务器
```bash
cd backend
npm run dev
```
### 2. 使用 REST Client 测试 API
在 VS Code 中安装 REST Client 插件,然后打开 `test-api.http` 文件,点击每个请求上方的 "Send Request" 按钮进行测试。
### 3. 使用 curl 测试
```bash
# 健康检查
curl http://localhost:3000/api/health
# 获取 LLM 配置列表
curl http://localhost:3000/api/llm-configs
# 获取数据源列表
curl http://localhost:3000/api/sources
# 获取主题列表
curl http://localhost:3000/api/topics
# 获取报告列表
curl http://localhost:3000/api/reports
# 获取资讯列表
curl http://localhost:3000/api/articles
# 获取采集日志统计
curl http://localhost:3000/api/collection-logs/stats
```
### 4. 测试 CRUD 操作
测试每个资源的增删改查操作,确保:
- 创建成功返回 201
- 查询成功返回 200
- 更新成功返回 200
- 删除成功返回 200
- 资源不存在返回 404
- 参数错误返回 400
### 5. 测试手动触发
```bash
# 手动触发采集
curl -X POST http://localhost:3000/api/sources/1/collect
# 手动生成报告
curl -X POST http://localhost:3000/api/topics/1/generate-report
```
检查日志,确认任务已触发。
## 预期产物
- ✅ LLM 配置 API 实现完成
- ✅ 数据源管理 API 实现完成
- ✅ 推送渠道管理 API 实现完成
- ✅ 主题管理 API 实现完成
- ✅ 报告查询 API 实现完成
- ✅ 资讯浏览 API 实现完成
- ✅ 采集监控 API 实现完成
- ✅ 手动触发 API 实现完成
- ✅ 所有路由注册完成
- ✅ API 测试通过
## API 文档
### 响应格式
所有 API 响应统一格式:
```typescript
{
success: boolean
data?: any
error?: {
code: string
message: string
details?: any
}
message?: string
}
```
### 分页参数
```
?page=1&limit=20
```
### 分页响应
```typescript
{
items: T[]
total: number
page: number
limit: number
totalPages: number
}
```
## 常见问题
### 问题 1:CORS 错误
**解决方案**:检查 `.env` 中的 `CORS_ORIGIN` 配置。
### 问题 2:404 错误
**解决方案**:检查路由是否正确注册,URL 是否正确。
### 问题 3:500 错误
**解决方案**:查看服务器日志,检查错误信息。
## 下一步
完成本任务后,继续 [任务 10:前端初始化](./10-frontend-setup.md)。