Key-Value Store (kv)
The kv component is Diom’s key-value store component.
It’s disk backed, and allows storing infinite keys with values up to a few MB in size (per value).
Setting keys (kv.set)
When storing data in kv you need to pass the wanted key and value, and you can optionally pass additional configuration.
Some of the values you can pass to kv.set:
key: a string with the key name.value: a byte array with the wanted value.ttl: optional expiry time, after which the key will be deleted.version: expected value version (see OCC section below)behavior: how to behave on conflicts. Allowed values:upsert(default): update if key exists, insert if doesn’t.insert: fail if key exists, insert if doesn’t.update: update if key exists, fail if doesn’t.
Example setting a value with a 60s TTL:
import { Diom } from "diom";
import { Temporal } from "temporal-polyfill-lite";
const client = new Diom("AUTH_TOKEN");
await client.kv.set("my-key", new TextEncoder().encode("value goes here"), {
behavior: "insert",
ttl: Temporal.Duration.from({ seconds: 60 }),
});Getting keys (kv.get)
Returns None when a value is not found.
const out = await client.kv.get("my-key", {});
if (out.value) {
console.log("Got:", new TextDecoder().decode(out.value));
} else {
console.log("Key not found");
}
console.log("Version:", out.version);Deleting keys (kv.delete)
To delete a key, call the kv.delete operation with the wanted key:
await client.kv.delete("my-key", {});Optimistic concurrency control (OCC)
Diom supports optimistic concurrency control as a way to ensure data consistency. This is achieved using the version parameter that’s supported by both kv.set and kv.delete.
The way it works is that when you fetch a key, you get a version identifier in addition to the value. You can then pass this version to subsequent calls to kv.set and kv.delete to ensure that the key hasn’t been written to since you last read the value.
Example code:
import { Temporal } from "temporal-polyfill-lite";
const key = "test-key";
// Set the key. Pass version 0 to enforce the key isn't already set.
await client.kv.set(key, new TextEncoder().encode("value 1"), { version: 0 });
// Get the value back
const out = await client.kv.get(key, {});
console.log("Got:", new TextDecoder().decode(out.value!));
console.log("Version:", out.version);
// Conditional write using the version token
await client.kv.set(key, new TextEncoder().encode("updated value"), { version: out.version });
// This write will fail, as version is stale.
await client.kv.set(key, new TextEncoder().encode("write will fail"), { version: out.version });
// This delete will fail, as version is stale.
await client.kv.delete(key, { version: out.version });