完善后端核心框架
- 添加错误处理中间件 (error-handler.ts) - 添加请求日志中间件 (request-logger.ts) - 添加健康检查路由 (health.ts) - 更新 app.ts 集成中间件和数据库连接 - 添加优雅关闭时断开数据库连接 Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
773fa369cd
commit
b8791ee556
4 files changed
+146
-25
No files matched your search
+22
-25
@@ -1,7 +1,11 @@
|
|||||||
import Fastify from 'fastify';
|
import Fastify from 'fastify';
|
||||||
import cors from '@fastify/cors';
|
import cors from '@fastify/cors';
|
||||||
import { config, validateConfig } from './config';
|
import { config, validateConfig } from './config';
|
||||||
|
import { connectDatabase, disconnectDatabase } from './config/database';
|
||||||
import logger from './utils/logger';
|
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';
|
||||||
|
|
||||||
// 验证配置
|
// 验证配置
|
||||||
try {
|
try {
|
||||||
@@ -27,42 +31,33 @@ async function registerPlugins(): Promise<void> {
|
|||||||
logger.info('CORS 插件已注册');
|
logger.info('CORS 插件已注册');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 注册中间件
|
||||||
|
async function registerMiddleware(): Promise<void> {
|
||||||
|
// 请求日志
|
||||||
|
app.addHook('onRequest', requestLogger);
|
||||||
|
logger.info('中间件已注册');
|
||||||
|
}
|
||||||
|
|
||||||
// 注册路由
|
// 注册路由
|
||||||
async function registerRoutes(): Promise<void> {
|
async function registerRoutes(): Promise<void> {
|
||||||
// 健康检查
|
// 健康检查路由
|
||||||
app.get('/api/v1/health', async () => {
|
await app.register(healthRoutes, { prefix: '/api/v1' });
|
||||||
return {
|
|
||||||
success: true,
|
|
||||||
data: {
|
|
||||||
status: 'ok',
|
|
||||||
timestamp: new Date().toISOString(),
|
|
||||||
version: '1.0.0',
|
|
||||||
},
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
logger.info('路由已注册');
|
logger.info('路由已注册');
|
||||||
}
|
}
|
||||||
|
|
||||||
// 错误处理
|
// 错误处理
|
||||||
app.setErrorHandler((error, request, reply) => {
|
app.setErrorHandler(errorHandler);
|
||||||
logger.error('请求处理错误:', {
|
|
||||||
error: error.message,
|
|
||||||
stack: error.stack,
|
|
||||||
url: request.url,
|
|
||||||
method: request.method,
|
|
||||||
});
|
|
||||||
|
|
||||||
reply.status(error.statusCode || 500).send({
|
|
||||||
success: false,
|
|
||||||
error: error.message || '服务器内部错误',
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// 启动服务器
|
// 启动服务器
|
||||||
async function start(): Promise<void> {
|
async function start(): Promise<void> {
|
||||||
try {
|
try {
|
||||||
|
// 连接数据库
|
||||||
|
await connectDatabase();
|
||||||
|
|
||||||
|
// 注册插件和中间件
|
||||||
await registerPlugins();
|
await registerPlugins();
|
||||||
|
await registerMiddleware();
|
||||||
await registerRoutes();
|
await registerRoutes();
|
||||||
|
|
||||||
await app.listen({
|
await app.listen({
|
||||||
@@ -71,7 +66,7 @@ async function start(): Promise<void> {
|
|||||||
});
|
});
|
||||||
|
|
||||||
logger.info(`🚀 服务器启动成功,监听端口 ${config.port}`);
|
logger.info(`🚀 服务器启动成功,监听端口 ${config.port}`);
|
||||||
logger.info(`📚 API 文档: http://localhost:${config.port}/api/v1/health`);
|
logger.info(`📚 健康检查: http://localhost:${config.port}/api/v1/health`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('服务器启动失败:', error);
|
logger.error('服务器启动失败:', error);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
@@ -93,12 +88,14 @@ process.on('unhandledRejection', (reason, promise) => {
|
|||||||
process.on('SIGTERM', async () => {
|
process.on('SIGTERM', async () => {
|
||||||
logger.info('SIGTERM 信号收到,正在关闭服务器...');
|
logger.info('SIGTERM 信号收到,正在关闭服务器...');
|
||||||
await app.close();
|
await app.close();
|
||||||
|
await disconnectDatabase();
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
process.on('SIGINT', async () => {
|
process.on('SIGINT', async () => {
|
||||||
logger.info('SIGINT 信号收到,正在关闭服务器...');
|
logger.info('SIGINT 信号收到,正在关闭服务器...');
|
||||||
await app.close();
|
await app.close();
|
||||||
|
await disconnectDatabase();
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import { FastifyError, FastifyReply, FastifyRequest } from 'fastify';
|
||||||
|
import { AppError, ValidationError } from '../../utils/errors';
|
||||||
|
import logger from '../../utils/logger';
|
||||||
|
|
||||||
|
export async function errorHandler(
|
||||||
|
error: FastifyError,
|
||||||
|
request: FastifyRequest,
|
||||||
|
reply: FastifyReply
|
||||||
|
): Promise<void> {
|
||||||
|
logger.error('请求处理错误:', {
|
||||||
|
method: request.method,
|
||||||
|
url: request.url,
|
||||||
|
error: error.message,
|
||||||
|
stack: error.stack,
|
||||||
|
});
|
||||||
|
|
||||||
|
// 处理自定义应用错误
|
||||||
|
if (error instanceof AppError) {
|
||||||
|
const response: any = {
|
||||||
|
success: false,
|
||||||
|
error: error.message,
|
||||||
|
};
|
||||||
|
|
||||||
|
// 如果是验证错误,附加详细信息
|
||||||
|
if (error instanceof ValidationError) {
|
||||||
|
response.details = error.errors;
|
||||||
|
}
|
||||||
|
|
||||||
|
reply.status(error.statusCode).send(response);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理 Fastify 验证错误
|
||||||
|
if (error.validation) {
|
||||||
|
reply.status(400).send({
|
||||||
|
success: false,
|
||||||
|
error: '请求参数验证失败',
|
||||||
|
details: error.validation,
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理未知错误
|
||||||
|
const statusCode = error.statusCode || 500;
|
||||||
|
const message = statusCode === 500 ? '服务器内部错误' : error.message;
|
||||||
|
|
||||||
|
reply.status(statusCode).send({
|
||||||
|
success: false,
|
||||||
|
error: message,
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { FastifyRequest, FastifyReply, HookHandlerDoneFunction } from 'fastify';
|
||||||
|
import logger from '../../utils/logger';
|
||||||
|
|
||||||
|
export function requestLogger(
|
||||||
|
request: FastifyRequest,
|
||||||
|
reply: FastifyReply,
|
||||||
|
done: HookHandlerDoneFunction
|
||||||
|
): void {
|
||||||
|
const start = Date.now();
|
||||||
|
|
||||||
|
// 记录请求开始
|
||||||
|
logger.debug(`--> ${request.method} ${request.url}`);
|
||||||
|
|
||||||
|
// 在响应发送后记录
|
||||||
|
reply.raw.on('finish', () => {
|
||||||
|
const duration = Date.now() - start;
|
||||||
|
const statusCode = reply.statusCode;
|
||||||
|
|
||||||
|
// 根据状态码选择日志级别
|
||||||
|
if (statusCode >= 500) {
|
||||||
|
logger.error(`<-- ${request.method} ${request.url} ${statusCode} ${duration}ms`);
|
||||||
|
} else if (statusCode >= 400) {
|
||||||
|
logger.warn(`<-- ${request.method} ${request.url} ${statusCode} ${duration}ms`);
|
||||||
|
} else {
|
||||||
|
logger.info(`<-- ${request.method} ${request.url} ${statusCode} ${duration}ms`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
done();
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import { FastifyInstance } from 'fastify';
|
||||||
|
import prisma from '../../config/database';
|
||||||
|
|
||||||
|
export async function healthRoutes(app: FastifyInstance): Promise<void> {
|
||||||
|
// 基础健康检查
|
||||||
|
app.get('/health', async (request, reply) => {
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
data: {
|
||||||
|
status: 'ok',
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
version: '1.0.0',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
// 详细健康检查(包括数据库)
|
||||||
|
app.get('/health/detailed', async (request, reply) => {
|
||||||
|
const checks: Record<string, string> = {
|
||||||
|
server: 'ok',
|
||||||
|
};
|
||||||
|
|
||||||
|
// 检查数据库连接
|
||||||
|
try {
|
||||||
|
await prisma.$queryRaw`SELECT 1`;
|
||||||
|
checks.database = 'ok';
|
||||||
|
} catch (error) {
|
||||||
|
checks.database = 'error';
|
||||||
|
}
|
||||||
|
|
||||||
|
const allOk = Object.values(checks).every((v) => v === 'ok');
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: allOk,
|
||||||
|
data: {
|
||||||
|
status: allOk ? 'ok' : 'degraded',
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
version: '1.0.0',
|
||||||
|
checks,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
Reference in new issue
Block a user