# API 文档 / API Reference

## 客户端拦截器 API / Client Interceptor API

### 导出方法 / Exported Functions

---

#### `initMockInterceptor(axiosInstance)`

初始化通用 Axios 拦截器

Initialize a generic Axios mock interceptor

**参数 / Parameters:**

| 参数名 | 类型 | 必填 | 说明 |
|--------|------|------|------|
| `axiosInstance` | `AxiosInstance` | ✅ | Axios 实例对象 |

**返回值 / Returns:** `Promise<void>`

**使用示例 / Usage Example:**

```typescript
import { initMockInterceptor } from 'vite-plugin-api-mmock/client'
import axios from 'axios'

await initMockInterceptor(axios)
```

---

#### `initMockInterceptorForPureHttp()`

初始化 PureHttp 封装的拦截器

Initialize mock interceptor for PureHttp wrapper

**参数 / Parameters:** 无

**返回值 / Returns:** `Promise<void>`

**使用示例 / Usage Example:**

```typescript
import {
  initMockInterceptorForPureHttp,
  registerHttpInstance
} from 'vite-plugin-api-mmock/client'
import { http } from './http'

// 必须先注册 http 实例
registerHttpInstance(http)

// 然后初始化拦截器
await initMockInterceptorForPureHttp()
```

---

#### `createMockInterceptor(options)`

创建自定义拦截器实例

Create a custom mock interceptor instance

**参数 / Parameters:**

| 参数名 | 类型 | 必填 | 说明 |
|--------|------|------|------|
| `options` | `MockInterceptorOptions` | ✅ | 拦截器配置对象 |

**MockInterceptorOptions 类型定义:**

| 属性 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `mockData` | `Record<string, MockBundleData>` | ✅ | Mock 数据对象，key 为请求标识 |
| `enabled` | `boolean \| (() => boolean)` | ❌ | 是否启用 mock，默认 false |
| `onMockHit` | `(url, method, mock) => void` | ❌ | Mock 命中时的回调 |
| `onBypass` | `(url, method, reason) => void` | ❌ | Mock 跳过时的回调 |

**返回值 / Returns:** `MockInterceptor` 实例

**使用示例 / Usage Example:**

```typescript
import { createMockInterceptor } from 'vite-plugin-api-mmock/client'

const interceptor = createMockInterceptor({
  mockData: {
    '/api/users/get.js': {
      enable: true,
      data: { users: [{ id: 1, name: 'Alice' }] },
      delay: 100,
      status: 200
    }
  },
  enabled: true,
  onMockHit: (url, method, mock) => {
    console.log(`[MOCK HIT] ${method} ${url}`)
  }
})

interceptor.setupAxios(axiosInstance)
```

---

#### `setMockEnabled(enabled)`

设置运行时 Mock 开关状态

Set mock enabled state at runtime

**参数 / Parameters:**

| 参数名 | 类型 | 必填 | 说明 |
|--------|------|------|------|
| `enabled` | `boolean` | ✅ | true 启用，false 禁用 |

**返回值 / Returns:** `void`

**使用示例 / Usage Example:**

```typescript
import { setMockEnabled } from 'vite-plugin-api-mmock/client'

// 启用 mock
setMockEnabled(true)

// 禁用 mock
setMockEnabled(false)
```

---

#### `isMockEnabled()`

获取当前 Mock 开关状态

Get current mock enabled state

**参数 / Parameters:** 无

**返回值 / Returns:** `boolean`

**使用示例 / Usage Example:**

```typescript
import { isMockEnabled } from 'vite-plugin-api-mmock/client'

if (isMockEnabled()) {
  console.log('Mock is currently enabled')
}
```

---

#### `registerHttpInstance(http)`

注册 PureHttp 实例（PureHttp 专用）

Register PureHttp instance (for PureHttp only)

**参数 / Parameters:**

| 参数名 | 类型 | 必填 | 说明 |
|--------|------|------|------|
| `http` | `HttpInstance` | ✅ | PureHttp 实例对象 |

**HttpInstance 类型要求:**

```typescript
interface HttpInstance {
  constructor: {
    axiosInstance: AxiosInstance
  }
}
```

**返回值 / Returns:** `void`

**使用示例 / Usage Example:**

```typescript
import { registerHttpInstance } from 'vite-plugin-api-mmock/client'
import { http } from './http'

registerHttpInstance(http)
```

---

#### `loadMockData()`

从服务器加载 mock 数据文件

Load mock data from server

**参数 / Parameters:** 无

**返回值 / Returns:** `Promise<Record<string, MockBundleData>>`

**使用示例 / Usage Example:**

```typescript
import { loadMockData } from 'vite-plugin-api-mmock/client'

const mockData = await loadMockData()
console.log('Loaded mock data:', mockData)
```

---

## 类型定义 / Type Definitions

### MockBundleData

单个 Mock 数据结构

```typescript
interface MockBundleData {
  enable: boolean      // 是否启用此 mock
  data: unknown        // 响应数据
  delay?: number       // 延迟毫秒数
  status?: number      // HTTP 状态码
  isBinary?: boolean   // 是否为二进制文件
}
```

### MockInterceptorOptions

拦截器配置选项

```typescript
interface MockInterceptorOptions {
  mockData: Record<string, MockBundleData>
  enabled?: boolean | (() => boolean)
  onMockHit?: (url: string, method: string, mock: MockBundleData) => void
  onBypass?: (url: string, method: string, reason: string) => void
}
```

---

## Mock 数据格式 / Mock Data Format

### Key 格式 / Key Format

支持两种格式：

1. **文件路径格式**: `/api/users/get.js`
2. **HTTP 方法格式**: `GET /api/users`

### 完整示例 / Complete Example

```json
{
  "/api/users/get.js": {
    "enable": true,
    "data": {
      "code": 0,
      "message": "success",
      "data": [
        { "id": 1, "name": "Alice" },
        { "id": 2, "name": "Bob" }
      ]
    },
    "delay": 100,
    "status": 200
  },
  "POST /api/login": {
    "enable": true,
    "data": {
      "code": 0,
      "message": "Login success",
      "data": { "token": "xxx" }
    },
    "delay": 500,
    "status": 200
  }
}
```

---

## 环境变量 / Environment Variables

### VITE_USE_MOCK

构建时配置 Mock 默认状态

Configure default mock state at build time

| 值 | 说明 |
|----|------|
| `'true'` | 默认启用 Mock |
| 未设置或其他值 | 默认禁用 Mock |

**使用方式:**

```bash
# .env
VITE_USE_MOCK=true
```

```typescript
// 代码中会自动读取
const isEnvEnabled = import.meta.env.VITE_USE_MOCK === 'true'
```

---

## 优先级 / Priority

运行时控制的优先级高于环境变量

Runtime control has higher priority than environment variables

```
setMockEnabled(true)  >  VITE_USE_MOCK='true'  >  enabled: false (配置)
```

---

## 完整使用示例 / Complete Usage Example

### PureHttp + Vite

```typescript
// vite.config.ts
import { automock } from 'vite-plugin-api-mmock'

export default {
  plugins: [
    automock({
      mockDir: 'mock',
      bundleMockData: true
    })
  ]
}

// src/api/index.ts
import {
  initMockInterceptorForPureHttp,
  setMockEnabled,
  registerHttpInstance
} from 'vite-plugin-api-mmock/client'
import { http } from './http'

// 注册实例
registerHttpInstance(http)

// 初始化拦截器
initMockInterceptorForPureHttp()
  .then(() => console.log('[Mock] Initialized'))
  .catch(err => console.error('[Mock] Failed:', err))

// 开发环境启用
if (import.meta.env.DEV) {
  setMockEnabled(true)
}
```

### Axios + Vite

```typescript
// vite.config.ts
import { automock } from 'vite-plugin-api-mmock'

export default {
  plugins: [
    automock({
      mockDir: 'mock',
      bundleMockData: true
    })
  ]
}

// src/main.ts
import { initMockInterceptor, setMockEnabled } from 'vite-plugin-api-mmock/client'
import axios from 'axios'

// 初始化拦截器
initMockInterceptor(axios)
  .then(() => console.log('[Mock] Initialized'))
  .catch(err => console.error('[Mock] Failed:', err))

// 开发环境启用
if (import.meta.env.DEV) {
  setMockEnabled(true)
}

// 运行时动态控制
setMockEnabled(false)  // 切换到真实 API
setMockEnabled(true)   // 切换回 Mock
```
