version: 1
id: api_response_schema
title: Unified API Response Envelope
sources:
  project_md:
    - path: openspec/project.md
      lines: "16-19"
  middleware:
    - path: api/middlewares/index.ts
      lines: "76-94"
  legacy_app:
    - path: api/app.ts
      lines: "45-66"

json_schema_draft: "2020-12"
schemas:
  Pagination:
    type: object
    required:
      - page
      - limit
      - total
      - pages
    properties:
      page:
        type: integer
        minimum: 1
      limit:
        type: integer
        minimum: 1
      total:
        type: integer
        minimum: 0
      pages:
        type: integer
        minimum: 0
    additionalProperties: true

  ApiResponse:
    type: object
    required:
      - success
    properties:
      success:
        type: boolean

      message:
        type: string

      data:
        description: |
          业务返回体，形态取决于具体接口：
          - 单对象 / 列表 / 聚合对象 / 统计对象
        nullable: true
        oneOf:
          - type: object
          - type: array
          - type: string
          - type: number
          - type: boolean

      pagination:
        $ref: "#/schemas/Pagination"

      errors:
        description: |
          业务校验错误明细（当前仅在部分接口中使用，如用户数据校验）。
        type: array
        items:
          type: string

      error:
        description: |
          兼容字段：`api/app.ts` 的错误/404 处理使用 `error` 字段。
        type: string

    additionalProperties: true

constraints:
  - id: envelope_is_best_effort
    status: implemented
    evidence:
      - api/middlewares/index.ts:76
    details: |
      响应格式化中间件仅在返回体不含 `success` 字段时进行包装：
      - 包装为 `{ success: true, data: <original> }`
      - 控制器自行返回 `{ success: boolean, ... }` 时不二次包装

  - id: legacy_error_shape_exists
    status: implemented
    evidence:
      - api/app.ts:45
      - api/app.ts:58
    details: |
      `api/app.ts` 的错误与 404 返回使用 `{ success: false, error: string }`，
      与 project.md 中的 `{ success, message, data }` 不完全一致。

examples:
  success_with_data:
    success: true
    data:
      id: "uuid"
  success_with_message_and_data:
    success: true
    message: "登录成功"
    data:
      token: "admin-token"
  success_with_pagination:
    success: true
    data: []
    pagination:
      page: 1
      limit: 10
      total: 0
      pages: 0
  error_with_message:
    success: false
    message: "参数不完整"
  error_with_errors_array:
    success: false
    message: "数据验证失败"
    errors:
      - "手机号格式不正确"
  legacy_error:
    success: false
    error: "API not found"

