Files
learn-ai/backend/src/web/routes/channels.ts
T

104 lines
2.9 KiB
TypeScript
Raw Normal View History

2026-02-04 21:42:25 +08:00
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('推送渠道不存在');
}
2026-02-05 15:23:37 +08:00
// 构建更新数据对象,只包含提供的字段
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;
2026-02-04 21:42:25 +08:00
const channel = await prisma.channel.update({
where: { id: parseInt(id) },
2026-02-05 15:23:37 +08:00
data: updateData,
2026-02-04 21:42:25 +08:00
});
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, '推送渠道删除成功');
});
}