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 valibotpnpm add valibotyarn add valibotbun add valibotnub add valibotaube add valibotFor 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.
Related
- For choosing types, see Value Model.
- For handling exceptions, see Handling Errors.