/**
 * 评论 API 响应接口
 */
interface CommentApiResponse {
    success: boolean;
    html?: string;
    msg?: string;
    commentCount?: string;
}

/**
 * 评论 API 模块
 * 负责与服务器通信,处理评论的发布和加载
 */
export class CommentApi {
    /**
     * 发表新评论
     * @param url 提交的URL
     * @param formData 表单数据
     * @returns 返回操作结果,包含成功状态、HTML内容、错误信息等
     */
    public async postComment(url: string, formData: FormData): Promise<CommentApiResponse> {
        try {
            const response = await fetch(url, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                },
            });

            const commentCount = response.headers.get('commentCount');

            const contentType = response.headers.get('content-type');
            if (contentType && contentType.includes('application/json')) {
                const data = await response.json();
                return { success: false, msg: data.msg || '提交失败' };
            }

            const html = await response.text();

            try {
                const json = JSON.parse(html);
                if (json && json.success === false) {
                    return { success: false, msg: json.msg };
                }
            } catch (e) {
                /* 不是 JSON 格式,假定为 HTML 成功响应 */
            }

            return {
                success: true,
                html,
                commentCount: commentCount || undefined,
            };
        } catch (error) {
            console.error('评论发布错误:', error);
            return { success: false, msg: '网络请求失败' };
        }
    }

    /**
     * 加载评论(刷新或分页)
     * @param url 请求的URL
     * @returns 返回操作结果,包含成功状态、HTML内容、评论数量等
     */
    public async loadComments(url: string): Promise<CommentApiResponse> {
        try {
            const response = await fetch(url, {
                method: 'GET',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                },
            });

            if (!response.ok) {
                const { logger } = await import('../ConsoleLogger.ts');
                logger.outPutError(`HTTP error! status: ${response.status}`);
                return { success: false, msg: `请求失败,状态码:${response.status}` };
            }

            const commentCount = response.headers.get('commentCount');
            const html = await response.text();

            return {
                success: true,
                html,
                commentCount: commentCount || undefined,
            };
        } catch (error) {
            console.error('评论加载错误:', error);
            return { success: false };
        }
    }
}
⚠⚠    以下内容为AI分析的结果,请根据实际情况进行判断。

这是一个用 TypeScript 编写的评论系统 API 模块,主要负责处理评论的发布和加载功能。让我来详细解释一下:

接口定义

interface CommentApiResponse {
    success: boolean;      // 操作是否成功
    html?: string;         // 返回的HTML内容(可选)
    msg?: string;          // 错误或提示信息(可选)
    commentCount?: string; // 评论数量(可选)
}

这个接口定义了API响应的标准格式,使用了可选属性(?:)来适应不同场景的返回数据。

CommentApi 类

1. postComment 方法 - 发表评论

这个方法处理评论的发布:

参数:

  • url: 提交评论的服务器端点
  • formData: 包含评论内容的表单数据

核心逻辑:

  1. 使用 fetch 发送 POST 请求
  2. 添加 X-Requested-With: XMLHttpRequest 头部,标识这是一个 AJAX 请求
  3. 从响应头中获取评论数量
  4. 智能响应处理
    • 如果响应是 JSON 格式 → 解析并返回错误信息
    • 如果响应是文本但可以解析为 JSON → 检查是否有错误
    • 否则假定为成功的 HTML 响应

2. loadComments 方法 - 加载评论

这个方法处理评论的加载(刷新或分页):

参数:

  • url: 请求评论数据的URL

核心逻辑:

  1. 发送 GET 请求
  2. 检查 HTTP 状态码
  3. 如果请求失败,使用动态导入的日志记录器记录错误
  4. 成功时返回 HTML 内容和评论数量

设计特点

  1. 错误处理完善:每个方法都有 try-catch 包装,确保异常不会导致程序崩溃

  2. 灵活的响应处理postComment 方法可以处理多种响应格式(JSON错误响应、HTML成功响应)

  3. 异步操作:使用 async/await 处理异步请求,代码更清晰

  4. TypeScript 类型安全:通过接口定义确保返回数据的类型安全

  5. 模块化设计:使用 export class 导出,便于在其他模块中使用

  6. 动态导入:在 loadComments 中使用动态导入日志模块,避免不必要的依赖加载

这个模块为评论系统提供了稳定可靠的API通信层,能够优雅地处理各种异常情况和响应格式。

评论加载中...