Files
learn-ai/backend/tests/helpers/app.ts
T

73 lines
2.3 KiB
TypeScript
Raw Normal View History

2026-02-05 15:23:37 +08:00
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));
}