> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sajuapi.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# 캐시 클리어

<Info>
  **v1 Enterprise API (Coming Soon)**

  이 엔드포인트는 Enterprise 버전에서 제공될 예정입니다.
  현재는 [v0 API](/api-reference/v0/overview)를 사용하세요.
</Info>

캐시된 데이터를 삭제합니다. 운세 데이터, 계산 결과 등 특정 유형의 캐시를 선택적으로 삭제할 수 있습니다.

<Warning>
  이 엔드포인트는 관리자 권한이 필요합니다. 캐시 삭제 후 일시적으로 응답 시간이 증가할 수 있습니다.
</Warning>

***

## Request Body 파라미터

<ParamField body="type" type="string" default="all">
  삭제할 캐시 유형입니다. `all`, `fortunes`, `calculations`, `profiles` 중 하나입니다.
</ParamField>

<ParamField body="profile_id" type="string">
  특정 프로필의 캐시만 삭제합니다. 지정하지 않으면 전체를 대상으로 합니다.
</ParamField>

<ParamField body="fortune_date" type="string">
  특정 날짜의 운세 캐시만 삭제합니다. ISO 8601 형식(YYYY-MM-DD)입니다.
</ParamField>

<ParamField body="confirm" type="boolean" required>
  캐시 삭제를 확인합니다. `true`로 설정해야 삭제가 진행됩니다.
</ParamField>

***

## Response

### 성공

캐시 삭제에 성공하면 삭제된 항목 수가 반환됩니다.

### 실패

| 상태 코드 | 에러 타입                  | 설명                  |
| ----- | ---------------------- | ------------------- |
| 400   | `validation_error`     | `confirm` 파라미터가 누락됨 |
| 401   | `authentication_error` | API 키가 유효하지 않음      |
| 403   | `forbidden`            | 관리자 권한이 없음          |
| 429   | `rate_limited`         | 요청 한도 초과            |

***

## 요청 예시

<CodeGroup>
  ```bash cURL theme={null}
  # 전체 캐시 삭제
  curl -X POST https://api.sajuapi.dev/v1/cache/clear \
    -H "X-API-Key: bs_live_xxx" \
    -H "Content-Type: application/json" \
    -d '{
      "type": "all",
      "confirm": true
    }'

  # 특정 프로필 캐시만 삭제
  curl -X POST https://api.sajuapi.dev/v1/cache/clear \
    -H "X-API-Key: bs_live_xxx" \
    -H "Content-Type: application/json" \
    -d '{
      "type": "fortunes",
      "profile_id": "prf_abc123def456",
      "confirm": true
    }'

  # 특정 날짜의 운세 캐시 삭제
  curl -X POST https://api.sajuapi.dev/v1/cache/clear \
    -H "X-API-Key: bs_live_xxx" \
    -H "Content-Type: application/json" \
    -d '{
      "type": "fortunes",
      "fortune_date": "2025-01-16",
      "confirm": true
    }'
  ```

  ```javascript JavaScript theme={null}
  // 전체 캐시 삭제
  const response = await fetch(
    'https://api.sajuapi.dev/v1/cache/clear',
    {
      method: 'POST',
      headers: {
        'X-API-Key': 'bs_live_xxx',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        type: 'all',
        confirm: true
      })
    }
  );

  const result = await response.json();
  console.log(`삭제된 항목: ${result.cleared_count}`);

  // 특정 프로필 캐시만 삭제
  const profileClear = await fetch(
    'https://api.sajuapi.dev/v1/cache/clear',
    {
      method: 'POST',
      headers: {
        'X-API-Key': 'bs_live_xxx',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        type: 'fortunes',
        profile_id: 'prf_abc123def456',
        confirm: true
      })
    }
  ).then(r => r.json());
  ```

  ```python Python theme={null}
  import requests

  # 전체 캐시 삭제
  response = requests.post(
      'https://api.sajuapi.dev/v1/cache/clear',
      headers={'X-API-Key': 'bs_live_xxx'},
      json={
          'type': 'all',
          'confirm': True
      }
  )

  result = response.json()
  print(f"삭제된 항목: {result['cleared_count']}")

  # 특정 프로필 캐시만 삭제
  profile_clear = requests.post(
      'https://api.sajuapi.dev/v1/cache/clear',
      headers={'X-API-Key': 'bs_live_xxx'},
      json={
          'type': 'fortunes',
          'profile_id': 'prf_abc123def456',
          'confirm': True
      }
  ).json()
  ```
</CodeGroup>

***

## 응답 예시

### 전체 캐시 삭제

```json theme={null}
{
  "success": true,
  "type": "all",
  "cleared": {
    "fortunes": 12580,
    "calculations": 5420,
    "profiles": 0
  },
  "cleared_count": 18000,
  "cleared_at": "2025-01-16T09:00:00Z"
}
```

### 특정 프로필 캐시 삭제

```json theme={null}
{
  "success": true,
  "type": "fortunes",
  "profile_id": "prf_abc123def456",
  "cleared": {
    "fortunes": 45
  },
  "cleared_count": 45,
  "cleared_at": "2025-01-16T09:00:00Z"
}
```

### 특정 날짜 캐시 삭제

```json theme={null}
{
  "success": true,
  "type": "fortunes",
  "fortune_date": "2025-01-16",
  "cleared": {
    "fortunes": 3250
  },
  "cleared_count": 3250,
  "cleared_at": "2025-01-16T09:00:00Z"
}
```

***

## CacheClearResult 객체

| 필드              | 타입      | 설명                     |
| --------------- | ------- | ---------------------- |
| `success`       | boolean | 삭제 성공 여부입니다.           |
| `type`          | string  | 삭제된 캐시 유형입니다.          |
| `profile_id`    | string  | 대상 프로필 ID입니다 (지정한 경우). |
| `fortune_date`  | string  | 대상 날짜입니다 (지정한 경우).     |
| `cleared`       | object  | 유형별 삭제된 항목 수입니다.       |
| `cleared_count` | integer | 총 삭제된 항목 수입니다.         |
| `cleared_at`    | string  | 삭제 완료 시간입니다.           |

***

## 캐시 유형

| 유형             | 설명          | TTL                 |
| -------------- | ----------- | ------------------- |
| `fortunes`     | 생성된 운세 캐시   | 24시간 (일간), 1주일 (연간) |
| `calculations` | 사주 계산 결과 캐시 | 영구 (프로필 삭제 시 삭제)    |
| `profiles`     | 프로필 조회 캐시   | 1시간                 |

***

## 활용 사례

### 운세 재생성

프로필 정보가 수정된 후 캐시를 삭제하여 새로운 운세를 생성할 수 있습니다.

```javascript theme={null}
// 프로필 수정 후 캐시 삭제
async function updateProfileAndClearCache(profileId, updateData) {
  // 1. 프로필 수정
  await fetch(`/v1/profiles/${profileId}`, {
    method: 'PUT',
    headers: {
      'X-API-Key': 'bs_live_xxx',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(updateData)
  });

  // 2. 해당 프로필의 캐시 삭제
  await fetch('/v1/cache/clear', {
    method: 'POST',
    headers: {
      'X-API-Key': 'bs_live_xxx',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      type: 'fortunes',
      profile_id: profileId,
      confirm: true
    })
  });

  // 3. 새로운 운세 생성
  const fortune = await fetch('/v1/fortunes', {
    method: 'POST',
    headers: {
      'X-API-Key': 'bs_live_xxx',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      profile_id: profileId,
      fortune_type: 'daily'
    })
  }).then(r => r.json());

  return fortune;
}
```

### 일괄 캐시 초기화

자정에 모든 일간 운세 캐시를 삭제하여 새로운 날의 운세를 준비할 수 있습니다.

```javascript theme={null}
// 자정에 실행 (Cron job)
async function resetDailyCache() {
  const yesterday = new Date();
  yesterday.setDate(yesterday.getDate() - 1);
  const dateStr = yesterday.toISOString().split('T')[0];

  const result = await fetch('/v1/cache/clear', {
    method: 'POST',
    headers: {
      'X-API-Key': 'bs_live_xxx',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      type: 'fortunes',
      fortune_date: dateStr,
      confirm: true
    })
  }).then(r => r.json());

  console.log(`어제(${dateStr}) 캐시 삭제: ${result.cleared_count}개`);
}
```

<Note>
  캐시 삭제는 감사 로그에 기록됩니다. 빈번한 캐시 삭제는 비용 증가로 이어질 수 있으므로 주의하세요.
</Note>
