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

Validating Values

How to validate keys and input/output values with Valibot schemas.

Use Valibot schema validation to catch input mistakes and corrupted stored data early.

Specify Schemas

Pass PlainValue() or StreamValue() combined with Valibot schemas to the Builder schema option. Install valibot separately.

npm install valibot
pnpm add valibot
yarn add valibot
bun add valibot
nub add valibot
aube add valibot

For literal key names, use the object form.

import * as unikvs from "unikvs";
import * as v from "valibot";

const kvs = new unikvs.Builder({
  schema: {
    message: unikvs.PlainValue(v.pipe(v.string(), v.minLength(1))),
  },
})
  .persist(storage)
  .build();

To dispatch by key pattern, use the array form. The first matching definition wins.

import * as unikvs from "unikvs";
import * as v from "valibot";

const kvs = new unikvs.Builder({
  schema: [
    [v.pipe(v.string(), v.regex(/^msg-.+/)), unikvs.PlainValue(v.string())],
    [v.pipe(v.string(), v.regex(/^img-.+/)), unikvs.StreamValue(v.instance(Uint8Array))],
  ],
})
  .persist(storage)
  .build();

Validation Scope

What each operation validates and the error on failure:

Operation What is validated Error on failure
set Validates the input value. InvalidInputError
get Validates the output value. InvalidOutputError
stream Validates each chunk. InvalidOutputError
has / delete Validates the key, array form only. InvalidInputError
await kvs.set("message", "hello");
await kvs.get("message"); // "hello"

// Fails input validation and throws InvalidInputError
await kvs.set("message", "");

Without Schemas

Omitting schema disables runtime validation. Only type-level restrictions remain.

import * as unikvs from "unikvs";

const kvs = new unikvs.Builder<{
  message: unikvs.PlainValue<string>;
}>()
  .persist(storage)
  .build();

To guarantee input shapes in production, choose the schema-based setup.

Was this page helpful?