@unikvs/cache-storage
How to use CacheStorage in @unikvs/cache-storage, a storage that keeps Responses in the Cache API.
Overview
@unikvs/cache-storage Browser only is a storage that keeps Response objects in the Cache API. Use it to cache fetched responses as-is.
nameisCacheStorage.- Requires
openandclose.openopens theCache. - Map logical keys to
Requestobjects withtoRequest. - Uses a dedicated
Cache, socleardeletes every enumerated request.
Install with:
npm install @unikvs/cache-storagepnpm add @unikvs/cache-storageyarn add @unikvs/cache-storagebun add @unikvs/cache-storagenub add @unikvs/cache-storageaube add @unikvs/cache-storageUsage
CacheStorage implements IStorage. Pass it to UniKvs with persist().
import { CacheStorage } from "@unikvs/cache-storage";
Constructor arguments:
The following example stores a Response and reads it back.
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
| Operation | Supported data type |
|---|---|
write/read |
Response |
getWritable/getReadable chunks |
Uint8Array<ArrayBuffer> |
- Stores
Responseobjects as-is. - Stream chunks support only
Uint8Array<ArrayBuffer>. - Streams from
getWritableconcatenate chunks and save them as aResponseonclose. - Streams from
getReadableemit the storedResponsebytes as a single chunk.
Errors
This package throws the following errors.
KeyNotFoundError
Meaning
Thrown when the specified key does not exist. A shared error from @unikvs/core.
How to fix
Check with exists before reading.
Example
The following example catches KeyNotFoundError.
import { KeyNotFoundError } from "@unikvs/cache-storage";
try {
await kvs.get("missing-key");
} catch (ex) {
if (ex instanceof KeyNotFoundError) {
console.log("Key not found");
} else {
throw ex;
}
}
CacheStorageNotAvailableError
Meaning
Thrown at open time when no Cache API is found. No caches was injected and the runtime has no Cache API.
How to fix
Inject a CacheStorage via options.caches or run in a supported browser.
InvalidChunkTypeError
Meaning
Thrown when a non-Uint8Array<ArrayBuffer> chunk is written to getWritable.
How to fix
Write Uint8Array chunks to streams.