Files
learn-ai/backend/src/web/routes/channels.ts
T
hughhuangandClaude Sonnet 4.5 697430feed 添加后端集成测试套件
- 实现 82 个集成测试用例覆盖所有 API 端点
- 使用真实数据库连接,无 mock 逻辑
- 修复 PUT 请求只更新提供字段的逻辑
- 配置 Vitest 串行执行避免测试竞态

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-05 15:23:37 +08:00

105 lines
2.9 KiB
TypeScript

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, '推送渠道删除成功');
});
}