---
title: "@unikvs/cache-storage"
description: "@unikvs/cache-storage の CacheStorage。Cache API に Response を保存するストレージの使い方を説明します。"
---

## 概要 [#overview]

`@unikvs/cache-storage` ブラウザー専用 は Cache API に `Response` を保存するストレージです。取得した応答をそのまま蓄えたい場合に使います。

- `name` は `CacheStorage` です。
- `open`・`close` が必要です。`open` は `Cache` を開きます。
- 論理キーから `Request` への変換は `toRequest` で指定します。
- 専用の `Cache` を使うので、`clear` は列挙した要求をすべて削除します。

インストールは次のコマンドで行います。

```package-install
npm install @unikvs/cache-storage
```

## 使い方 [#usage]

CacheStorage は IStorage を実装しています。UniKvs には persist() で渡します。

```ts
import { CacheStorage } from "@unikvs/cache-storage";
```

コンストラクターの引数は次のとおりです。

| Prop | Type | Default | Description |
| - | - | - | - |
| `cacheName` | `[#cache-name] string` | - | 使う Cache の名前です。 |
| `toRequest` | `[#to-request] IToRequest` | - | 論理キーを Request に変換する関数です。 |
| `caches?` | `[#caches] CacheStorage \| undefined` | - | 使う Cache API の CacheStorage です。省略した場合は実行環境の Cache API を使います。 |

以下は、`Response` を保存して読み戻す例です。

```ts
import { CacheStorage } from "@unikvs/cache-storage";
import * as unikvs from "unikvs";

const kvs = new unikvs.Builder<{
  page: unikvs.PlainValue<Response>;
}>()
  .persist(
    new CacheStorage({
      cacheName: "unikvs",
      toRequest: (key) => `/kvs/${key}`,
    }),
  )
  .build();

await kvs.open();
await kvs.set("page", new Response("hello"));

const res = await kvs.get("page");
console.log(await res.text()); // "hello"

await kvs.close();
```

## データ型 [#data-types]

| 操作                                    | 対応するデータ型          |
| --------------------------------------- | ------------------------- |
| `write`・`read`                         | `Response`                |
| `getWritable`・`getReadable` のチャンク | `Uint8Array<ArrayBuffer>` |

- `Response` をそのまま保存します。
- ストリームのチャンクは `Uint8Array<ArrayBuffer>` のみに対応します。
- `getWritable` で取得したストリームは、チャンクを結合し、`close` 時に `Response` として保存します。
- `getReadable` で取得したストリームは、保存した `Response` のバイト列を単一チャンクとして送出します。

## エラー [#errors]

このパッケージが投げるエラーは次のとおりです。

### KeyNotFoundError [#key-not-found-error]

#### 意味

指定したキーが存在しない場合に投げます。`@unikvs/core` の共通エラーです。

#### 対処方法

`exists` で確認してから読み出してください。

#### 例

以下は、`KeyNotFoundError` を捕捉する例です。

```ts
import { KeyNotFoundError } from "@unikvs/cache-storage";

try {
  await kvs.get("missing-key");
} catch (ex) {
  if (ex instanceof KeyNotFoundError) {
    console.log("キーが見つかりません");
  } else {
    throw ex;
  }
}
```

### CacheStorageNotAvailableError [#cache-storage-not-available-error]

#### 意味

`open` 時に Cache API が見つからない場合に投げます。注入された `caches` がなく、実行環境にも Cache API がありません。

#### 対処方法

`options.caches` に `CacheStorage` を注入するか、対応するブラウザーで使ってください。

### InvalidChunkTypeError [#invalid-chunk-type-error]

| Prop | Type | Default | Description |
| - | - | - | - |
| `key` | `[#invalid-chunk-type-key] string` | - | 操作対象のキーです。 |
| `chunk` | `[#invalid-chunk-type-chunk] unknown` | - | 受け取ったチャンクの値です。 |
| `chunkType` | `[#invalid-chunk-type-chunk-type] string` | - | 受け取ったチャンクの型名です。 |

#### 意味

`getWritable` に `Uint8Array<ArrayBuffer>` 以外のチャンクを書き込んだ場合に投げます。

#### 対処方法

ストリームには `Uint8Array` のチャンクを書き込んでください。
