@unikvs/cache-storage
@unikvs/cache-storage の CacheStorage。Cache API に Response を保存するストレージの使い方を説明します。
概要
@unikvs/cache-storage ブラウザー専用 は Cache API に Response を保存するストレージです。取得した応答をそのまま蓄えたい場合に使います。
nameはCacheStorageです。open・closeが必要です。openはCacheを開きます。- 論理キーから
Requestへの変換はtoRequestで指定します。 - 専用の
Cacheを使うので、clearは列挙した要求をすべて削除します。
インストールは次のコマンドで行います。
npm install @unikvs/cache-storagepnpm add @unikvs/cache-storageyarn add @unikvs/cache-storagebun add @unikvs/cache-storagenub add @unikvs/cache-storageaube add @unikvs/cache-storage使い方
CacheStorage は IStorage を実装しています。UniKvs には persist() で渡します。
import { CacheStorage } from "@unikvs/cache-storage";
コンストラクターの引数は次のとおりです。
プロパティ型
以下は、Response を保存して読み戻す例です。
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();
データ型
| 操作 | 対応するデータ型 |
|---|---|
write・read |
Response |
getWritable・getReadable のチャンク |
Uint8Array<ArrayBuffer> |
Responseをそのまま保存します。- ストリームのチャンクは
Uint8Array<ArrayBuffer>のみに対応します。 getWritableで取得したストリームは、チャンクを結合し、close時にResponseとして保存します。getReadableで取得したストリームは、保存したResponseのバイト列を単一チャンクとして送出します。
エラー
このパッケージが投げるエラーは次のとおりです。
KeyNotFoundError
意味
指定したキーが存在しない場合に投げます。@unikvs/core の共通エラーです。
対処方法
exists で確認してから読み出してください。
例
以下は、KeyNotFoundError を捕捉する例です。
import { KeyNotFoundError } from "@unikvs/cache-storage";
try {
await kvs.get("missing-key");
} catch (ex) {
if (ex instanceof KeyNotFoundError) {
console.log("キーが見つかりません");
} else {
throw ex;
}
}
CacheStorageNotAvailableError
意味
open 時に Cache API が見つからない場合に投げます。注入された caches がなく、実行環境にも Cache API がありません。
対処方法
options.caches に CacheStorage を注入するか、対応するブラウザーで使ってください。
InvalidChunkTypeError
プロパティ型
意味
getWritable に Uint8Array<ArrayBuffer> 以外のチャンクを書き込んだ場合に投げます。
対処方法
ストリームには Uint8Array のチャンクを書き込んでください。