App patterns · real, tested code

Build a Persistent Key-Value Store in Larzscript

Insert, update and query records that survive the process exiting - a tiny document store backed by a plain JSON file.

Every read returns a deep copy, so mutating a record you got back from get()/find() can never silently corrupt the store; save() flushes to disk and a fresh store.open() on the same path picks up exactly what was there.

larzscript pkg install store

Code

import "store" as store

let s = store.open("/tmp/kv-demo.json")
let id = store.insert(s, {"key": "theme", "value": "dark"})
print(store.get(s, id))
store.update(s, id, {"value": "light"})
print(store.get(s, id))
print(store.find(s, fn(r) { return r["key"] == "theme" }))
store.save(s)

let reopened = store.open("/tmp/kv-demo.json")
print(store.get(reopened, id))
Output
{key: theme, value: dark}
{key: theme, value: light}
[{key: theme, value: light}]
{key: theme, value: light}