@unikvs/http
How to use Http in @unikvs/http, a storage that keeps bytes on an HTTP server.
Overview
@unikvs/http is a storage that exchanges bytes with an HTTP server. Use it with a server supporting PUT, GET, HEAD, and DELETE.
nameisHttp.isOpenis alwaystrue.openandcloseperform no setup or teardown.- This storage appends
keyPrefixto keys, URL-encodes them, and places them underbaseUrl. - Headers and tokens can be overridden per operation via runtime variables, in addition to the constructor.
Install with:
npm install @unikvs/httppnpm add @unikvs/httpyarn add @unikvs/httpbun add @unikvs/httpnub add @unikvs/httpaube add @unikvs/httpUsage
Http implements IStorage. Pass it to UniKvs with persist().
import { Http } from "@unikvs/http";
Constructor arguments:
baseUrlstring
Base URL. Specify an absolute URL without query or fragment.
stringkeyPrefix?string | undefined
Prefix attached to every key.
string | undefined"unikvs:"allowClearWithoutPrefix?boolean | undefined
Whether to allow clear with an empty prefix.
boolean | undefinedfalsefetch?IFetch | undefined
fetch implementation to use. Pass a function taking a Request and returning a Response. Uses globalThis.fetch when omitted.
IFetch | undefinedheaders?Record<string, string> | undefined
Default request headers. Can be overridden with runtime variables.
Record<string, string> | undefinedtoken?string | undefined
Default bearer token. Specify a non-empty string. Can be overridden with runtime variables.
string | undefinedThe following example stores bytes and reads them back.
import { Http } from "@unikvs/http";
import * as unikvs from "unikvs";
const kvs = new unikvs.Builder<{
image: unikvs.Value<Uint8Array>;
}>()
.persist(new Http("https://example.com/kvs"))
.build();
await kvs.open();
await kvs.set("image", new Uint8Array([0, 1, 2]));
const bytes = await kvs.get("image");
console.log(bytes); // Uint8Array(3) [0, 1, 2]
await kvs.close();
Data types
| Operation | Supported data type |
|---|---|
write/read |
Uint8Array<ArrayBuffer> |
getWritable/getReadable chunks |
Uint8Array<ArrayBuffer> |
- Stores bytes only. Convert strings and other values to bytes before passing them.
- This storage handles
writewithPUT,readwithGET, andexistswithHEAD(falling back toGETwhen unsupported). deletesucceeds even for missing keys.clearrequests deletion under the prefix withDELETE. ThrowsClearNotSupportedErrorwhen the server does not support it.getWritablebuffers chunks and sends them at once withPUTonclose.getReadablereturns theGETresponse body as-is. Returns an empty stream when there is no body.
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/http";
try {
await kvs.get("missing-key");
} catch (ex) {
if (ex instanceof KeyNotFoundError) {
console.log("Key not found");
} else {
throw ex;
}
}
InvalidBaseUrlError
actualunknown
The received baseUrl value.
unknownMeaning
Thrown when the constructor baseUrl is not an absolute URL. Leading/trailing whitespace, empty strings, relative URLs, and URLs with query or fragment are rejected.
How to fix
Specify an absolute URL without query or fragment.
InvalidHeadersError
actualunknown
The received headers value.
unknownMeaning
Thrown when headers are not an object with string values. Both constructor headers and runtime-variable headers are validated.
How to fix
Make every header value a string.
InvalidTokenError
actualunknown
The received token value.
unknownMeaning
Thrown when the token is not a non-empty string. Both constructor token and runtime-variable tokens are validated.
How to fix
Specify a non-empty string for the token.
InvalidKeyError
keystring
The key that could not be encoded.
stringMeaning
Thrown when a key cannot be encoded as a URL path segment.
How to fix
Use an encodable key.
ClearWithoutPrefixNotAllowedError
Meaning
Thrown when clear is called with an empty keyPrefix while allowClearWithoutPrefix is still false.
How to fix
Set a non-empty keyPrefix or pass allowClearWithoutPrefix: true.
ClearNotSupportedError
Meaning
Thrown when the server responds to clear with 404, 405, or 501. The server does not support prefix deletion.
How to fix
Implement prefix deletion on the server, or stop calling clear.
HttpNetworkError
Meaning
Thrown when fetch itself fails. Abortion-driven failures are excluded.
How to fix
Check the network and server status, and retry if needed.
HttpResponseError
methodstring
Method of the failed request.
stringurlstring
URL of the failed request.
stringstatusnumber
Status returned by the server.
numberstatusTextstring
Status text returned by the server.
stringkeystring | undefined
Key being operated on. undefined for failed clear.
string | undefinedMeaning
Thrown on unexpected response statuses. 404/410 on read and getReadable become KeyNotFoundError, 404/410 on delete become success, and 404/405/501 on clear become ClearNotSupportedError.
How to fix
Check the response with meta.status and meta.statusText.
InvalidChunkTypeError
Meaning
Thrown when a non-Uint8Array<ArrayBuffer> chunk is written to getWritable.
How to fix
Write Uint8Array chunks to streams.