@unikvs/localstorage
Usage of LocalStorage in @unikvs/localstorage, a storage that keeps strings in localStorage.
Overview
@unikvs/localstorage Browser only Usage of LocalStorage in @unikvs/localstorage, a storage that keeps strings in localStorage.
nameisLocalStorage.isOpenis alwaystrue.openchecks availability;closedoes nothing.- Logical keys are stored with
keyPrefixprepended.
Install with:
npm install @unikvs/localstoragepnpm add @unikvs/localstorageyarn add @unikvs/localstoragebun add @unikvs/localstoragenub add @unikvs/localstorageaube add @unikvs/localstorageUsage
LocalStorage implements IStorage. Pass it to UniKvs with persist().
import { LocalStorage } from "@unikvs/localstorage";
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.localStorage when omitted.
Storage | undefinedThe following example stores a string and reads it back.
import { LocalStorage } from "@unikvs/localstorage";
import * as unikvs from "unikvs";
const kvs = new unikvs.Builder<{
greeting: unikvs.PlainValue<string>;
}>()
.persist(new LocalStorage())
.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/localstorage";
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 localStorage.
How to fix
Set a non-empty keyPrefix or pass allowClearWithoutPrefix: true.
LocalStorageNotAvailableError
Meaning
Thrown when operating in an environment without localStorage. No storage was injected and the runtime has no localStorage.
How to fix
Inject a Storage via options.storage or run in a supported browser.