@unikvs/session-storage
Usage of SessionStorage in @unikvs/session-storage, a storage that keeps strings in sessionStorage.
Overview
@unikvs/session-storage Browser only Usage of SessionStorage in @unikvs/session-storage, a storage that keeps strings in sessionStorage.
nameisSessionStorage.isOpenis alwaystrue.openchecks availability;closedoes nothing.- Logical keys are stored with
keyPrefixprepended.
Install with:
npm install @unikvs/session-storagepnpm add @unikvs/session-storageyarn add @unikvs/session-storagebun add @unikvs/session-storagenub add @unikvs/session-storageaube add @unikvs/session-storageUsage
SessionStorage implements IStorage. Pass it to UniKvs with persist().
import { SessionStorage } from "@unikvs/session-storage";
Constructor arguments:
keyPrefix?string | undefined
Prefix attached to every key.
string | undefined"unikvs:"allowClearWithoutPrefix?boolean | undefined
Whether to allow clear with an empty prefix.
boolean | undefinedfalsestorage?Storage | undefined
The Storage to use. Uses globalThis.sessionStorage when omitted.
Storage | undefinedThe following example stores a string and reads it back.
import { SessionStorage } from "@unikvs/session-storage";
import * as unikvs from "unikvs";
const kvs = new unikvs.Builder<{
greeting: unikvs.PlainValue<string>;
}>()
.persist(new SessionStorage())
.build();
await kvs.open();
await kvs.set("greeting", "hello");
const value = await kvs.get("greeting");
console.log(value); // "hello"
await kvs.close();
Data types
| Operation | Supported data type |
|---|---|
write / read |
Strings |
- Stores strings only.
- Convert objects and other values to strings before passing them.
- Streams (
getWritable/getReadable) are not supported.
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/session-storage";
try {
await kvs.get("missing-key");
} catch (ex) {
if (ex instanceof KeyNotFoundError) {
console.log("Key not found");
} else {
throw ex;
}
}
ClearWithoutPrefixNotAllowedError
Meaning
Thrown when clear is called with an empty keyPrefix while allowClearWithoutPrefix is still false. This guard prevents wiping the whole sessionStorage.
How to fix
Set a non-empty keyPrefix or pass allowClearWithoutPrefix: true.
SessionStorageNotAvailableError
Meaning
Thrown when operating in an environment without sessionStorage. No storage was injected and the runtime has no sessionStorage.
How to fix
Inject a Storage via options.storage or run in a supported browser.