import { NextResponse } from "next/server"; import { AppError } from "../errors/app-error"; export interface ApiResponse { success: boolean; data?: T; error?: { message: string; code?: string; details?: unknown; }; meta?: { timestamp: string; requestId?: string; }; } export class ApiResponseHandler { /** * 成功响应 */ static success( data: T, statusCode: number = 200, meta?: { requestId?: string } ): NextResponse> { const response: ApiResponse = { success: true, data, meta: { timestamp: new Date().toISOString(), ...meta, }, }; return NextResponse.json(response, { status: statusCode }); } /** * 错误响应 */ static error( error: AppError | Error, meta?: { requestId?: string } ): NextResponse { const isAppError = error instanceof AppError; const statusCode = isAppError ? error.statusCode : 500; const code = isAppError ? error.code : "INTERNAL_SERVER_ERROR"; const response: ApiResponse = { success: false, error: { message: error.message, code, details: isAppError && !error.isOperational ? error.stack : undefined, }, meta: { timestamp: new Date().toISOString(), ...meta, }, }; return NextResponse.json(response, { status: statusCode }); } /** * 分页响应 */ static paginated( data: T[], pagination: { page: number; limit: number; total: number; totalPages: number; }, meta?: { requestId?: string } ): NextResponse> { const response: ApiResponse<{ data: T[]; pagination: typeof pagination }> = { success: true, data: { data, pagination, }, meta: { timestamp: new Date().toISOString(), ...meta, }, }; return NextResponse.json(response, { status: 200 }); } /** * 创建响应 */ static created( data: T, meta?: { requestId?: string } ): NextResponse> { return this.success(data, 201, meta); } /** * 无内容响应 */ static noContent(): NextResponse { return new NextResponse(null, { status: 204 }); } }