Skip to content
UniKVS
Esc
↑↓navigate↵open⌘Jpreview
On this page

@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.

  • name is Http.
  • isOpen is always true. open and close perform no setup or teardown.
  • This storage appends keyPrefix to keys, URL-encodes them, and places them under baseUrl.
  • Headers and tokens can be overridden per operation via runtime variables, in addition to the constructor.

Install with:

npm install @unikvs/http
pnpm add @unikvs/http
yarn add @unikvs/http
bun add @unikvs/http
nub add @unikvs/http
aube add @unikvs/http

Usage

Http implements IStorage. Pass it to UniKvs with persist().

import { Http } from "@unikvs/http";

Constructor arguments:

PropType
baseUrlstring

Base URL. Specify an absolute URL without query or fragment.

Typestring
keyPrefix?string | undefined

Prefix attached to every key.

Typestring | undefined
Default"unikvs:"
allowClearWithoutPrefix?boolean | undefined

Whether to allow clear with an empty prefix.

Typeboolean | undefined
Defaultfalse
fetch?IFetch | undefined

fetch implementation to use. Pass a function taking a Request and returning a Response. Uses globalThis.fetch when omitted.

TypeIFetch | undefined
headers?Record<string, string> | undefined

Default request headers. Can be overridden with runtime variables.

TypeRecord<string, string> | undefined
token?string | undefined

Default bearer token. Specify a non-empty string. Can be overridden with runtime variables.

Typestring | undefined

The 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 write with PUT, read with GET, and exists with HEAD (falling back to GET when unsupported).
  • delete succeeds even for missing keys.
  • clear requests deletion under the prefix with DELETE. Throws ClearNotSupportedError when the server does not support it.
  • getWritable buffers chunks and sends them at once with PUT on close.
  • getReadable returns the GET response 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

PropType
actualunknown

The received baseUrl value.

Typeunknown

Meaning

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

PropType
actualunknown

The received headers value.

Typeunknown

Meaning

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

PropType
actualunknown

The received token value.

Typeunknown

Meaning

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

PropType
keystring

The key that could not be encoded.

Typestring

Meaning

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

PropType
prefixstring

The prefix attempted to delete.

Typestring
statusnumber

The status returned by the server.

Typenumber

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

PropType
methodstring

Method of the failed request.

Typestring
urlstring

URL of the failed request.

Typestring
keystring | undefined

Key being operated on. undefined for failed clear.

Typestring | undefined

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

PropType
methodstring

Method of the failed request.

Typestring
urlstring

URL of the failed request.

Typestring
statusnumber

Status returned by the server.

Typenumber
statusTextstring

Status text returned by the server.

Typestring
keystring | undefined

Key being operated on. undefined for failed clear.

Typestring | undefined

Meaning

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

PropType
keystring

The key being operated on.

Typestring
chunkunknown

The received chunk value.

Typeunknown
chunkTypestring

The type name of the received chunk.

Typestring

Meaning

Thrown when a non-Uint8Array<ArrayBuffer> chunk is written to getWritable.

How to fix

Write Uint8Array chunks to streams.

Was this page helpful?