响应

在 XinAdmin 项目中,API 响应遵循统一的格式,确保前后端交互的一致性和可预测性。本文档详细说明了后端 API 的响应结构和前端的处理方式。

响应结构

后端 API 的响应遵循以下统一的数据结构:

{
  "success": true,
  "msg": "操作成功",
  "data": {},
  "showType": 0
}

各字段说明如下:

字段 类型 说明
success boolean 请求是否成功
msg string 响应消息,用于向用户显示操作结果
data any 响应数据,可能为对象、数组或 null
showType number 消息显示类型,用于前端 UI 提示

响应类型

showType 字段定义了前端消息提示的类型,具体值如下:

类型 说明
0 SUCCESS_MESSAGE 成功消息
1 WARN_MESSAGE 警告消息
2 ERROR_MESSAGE 错误消息
3 SUCCESS_NOTIFICATION 成功通知
4 WARN_NOTIFICATION 警告通知
5 ERROR_NOTIFICATION 错误通知
99 SILENT 静默响应(不显示消息)

成功响应

成功响应表示操作执行成功,通常返回操作结果数据或确认信息。

// 使用 success 方法返回成功响应
$this->success(['user' => $user], '用户创建成功');

// 或使用 throwSuccess 方法抛出成功响应
$this->throwSuccess(['user' => $user], '用户创建成功');

错误响应

错误响应用于表示操作失败或出现异常,会返回错误信息。

// 使用 error 方法返回错误响应
$this->error([], '操作失败:用户已存在');

// 或使用 throwError 方法抛出错误响应
$this->throwError([], '操作失败:用户已存在');

警告响应

警告响应用于表示操作虽然执行,但存在需要注意的情况。

// 使用 warn 方法返回警告响应
$this->warn([], '密码强度较低,建议修改');

// 或使用 throwWarn 方法抛出警告响应
$this->throwWarn([], '密码强度较低,建议修改');

通知响应

通知响应用于显示带有描述信息的通知,通常在右上角显示。

// 使用 notification 方法返回通知响应
$this->notification(
    '操作完成', 
    '您的文件已上传成功', 
    ShopTypeEnum::SUCCESS_NOTIFICATION,
    'topRight'
);

列表响应

对于列表数据,使用统一的分页格式:

{
  "success": true,
  "msg": "获取成功",
  "data": {
    "data": [
      // 数据列表
    ],
    "page": 1,
    "total": 100,
    "per_page": 10,
    "current_page": 1
  },
  "showType": 0
}

前端处理

前端使用 TypeScript 接口定义了响应结构,确保类型安全:

declare namespace API {
  type ErrorShowType =
    | 0      // Success Message
    | 1      // Warning Message
    | 2      // Error Message
    | 3      // Success Notification
    | 4      // Warning Notification
    | 5      // Error Notification
    | 99;    // Other

  /** List response data format */
  type ListResponse<T> = {
    data: T[]
    page: number
    total: number
    per_page: number
    current_page: number
  }

  /** The response data format agreed upon with the back end */
  interface ResponseStructure<T> {
    success: boolean
    msg: string
    data?: T
    errorCode?: number
    showType?: ErrorShowType
    status?: number
    description?: string
    placement?: 'top' | 'topLeft' | 'topRight' | 'bottom' | 'bottomLeft' | 'bottomRight',
  }
}

异常处理

后端异常处理会自动转换为标准响应格式。当抛出 HttpResponseException 时,会被异常处理器捕获并转换为 JSON 响应:

class HttpResponseException extends RuntimeException
{
    public function toArray(): array
    {
        return [
            'data' => $this->data,
            'success' => $this->success,
            'msg' => $this->msg,
            'showType' => $this->showType->value,
        ];
    }
}

通过这种统一的响应格式,XinAdmin 实现了前后端的解耦,并确保了用户界面提示的一致性。