Store
A store keeps your app's data on the device. It holds named documents, collections and properties, records every change, and validates data against a schema per app version. CloudStore is a Store that can also sync; without a cloud option it behaves exactly like Store.
Install
deno add jsr:@civility/cloud
Store, CloudStore and BlobStore come from @civility/cloud. Storage backends come from @civility/cloud/storage/<medium>.
Create a store
import { CloudStore } from '@civility/cloud'
import { IDBStorage } from '@civility/cloud/storage/idb'
type Settings = { colorScheme: 'auto' | 'light' | 'dark' }
type Item = { title: string; done: boolean }
const store = new CloudStore({
id: 'app-k3m7q2x4p6w5z7n3b2v4c6h5',
storage: { db: new IDBStorage() },
documents: ['settings'],
collections: ['items'],
versions: [{
version: '1.0.0',
schema: {
type: 'object',
properties: {
settings: { type: 'object' },
items: { type: 'object' },
},
},
}],
})
const settings = store.document<Settings>('settings', { colorScheme: 'auto' })
const items = store.collection<Item>('items')
await store.ready()
| Option | Type | Notes |
|---|---|---|
storage.db |
StoreDatabase |
Required. Where records are kept. |
storage.blobs |
BlobStorage | BlobStore |
Optional. Where binary data is kept. store.blobs throws without it. |
id |
string |
Local storage name. Backends created without their own id use it. |
documents |
string[] |
Names of single-object entities. |
collections |
string[] |
Names of keyed-record entities. |
properties |
string[] |
Names of single-primitive entities. |
versions |
StoreVersion[] |
Schema per app version, oldest first. See Schema versions. |
entities |
Record<string, { sync?, history? }> |
Per-entity overrides. Both default to true. |
blobs |
{ history?, historyByBlob?, referenceExtractors? } |
Blob history retention and custom blob-reference extractors. |
A persistent backend needs an id, either its own (new IDBStorage({ id })) or the store's. You must declare an entity name before you ask for it: store.collection('x') throws if x is not in collections.
Each version's schema is a JSON Schema whose root properties are the entity names. For a collection, the property describes one record. With Zod, generate it with z.toJSONSchema().
Entities
| Entity | Holds | Handle |
|---|---|---|
Document<T> |
One JSON object, such as settings. | store.document<T>(name, defaultValue) |
Collection<T> |
Many records, each with a string id. | store.collection<T>(name) |
Property<T> |
One string, number or boolean. |
store.property<T>(name, defaultValue) |
Collection
await items.set('item-1', { title: 'Buy milk', done: false }) // create or replace
await items.get('item-1') // Item | null
await items.has('item-1') // boolean
await items.update('item-1', { done: true }) // merge fields; throws if missing
await items.delete('item-1')
await items.list() // string[] of ids
await items.getAll() // Map<string, Item>
await items.find((item) => !item.done) // { id, data } | undefined
There is no add. Choose the id yourself, for example crypto.randomUUID().
Document
await settings.get() // Settings; the default value until first written
await settings.set({ colorScheme: 'dark' })
await settings.update({ colorScheme: 'light' })
await settings.delete() // back to the default value
Reading without await
value is a synchronous cache for render code. On a document or collection it is undefined until the data has been loaded, so call preload() first. After that, writes and synced changes keep it current.
await items.preload()
items.value // Map<string, Item>
Subscriptions
const sub = items.subscribe('item-1', (item) => {/* null when deleted */})
items.subscribeAll((id, item) => {})
settings.subscribe((value) => {})
store.subscribe((entity, id, data) => {/* id is null for documents */})
sub.unsubscribe()
Subscribers run for local writes and for changes pulled by sync.
History
Each write is stored as a change. items.getHistory(id) returns a record's changes, newest first, and items.getStateAt(id, changeId) rebuilds an earlier state. Documents have the same methods without the id argument. An entity declared with history: false keeps only its latest value, and these methods throw.
Store methods
| Method | Does |
|---|---|
ready() |
Resolves when storage is open and renames have run. |
subscribe(fn) |
Calls fn(entity, id, data, change?) for every change. |
batch(fn) |
Runs fn(store); subscribers are notified once per record, at the end. |
registerMergeStrategy(entity, path, strategy) |
Sets how concurrent edits to one field merge: 'array-union', 'map-merge', 'lww' or a function. |
export(options?) |
Returns all entities and their history as JSON. |
import(data, options?) |
Loads an export. |
deleteAll() |
Deletes all data. The deletions sync to other devices. |
clearAll() |
Wipes documents and collections on this device only. Properties are kept. |
resetLocal(options?) |
Erases all local data and blobs and retires the store. Create a new one after. |
dispose() |
Releases the store. |
By default, when two devices edit the same record, the newer change wins. Register the same merge strategies on every device.
Blobs
Store binary data such as images as blobs, and keep a reference to each blob in a record.
import { CloudStore } from '@civility/cloud'
import { IDBBlobStorage, IDBStorage } from '@civility/cloud/storage/idb'
type Photo = { caption: string; hash: string; mime: string; size: number }
const store = new CloudStore({
id: 'app-k3m7q2x4p6w5z7n3b2v4c6h5',
storage: { db: new IDBStorage(), blobs: new IDBBlobStorage() },
collections: ['photos'],
versions: [{
version: '1.0.0',
schema: { type: 'object', properties: { photos: { type: 'object' } } },
}],
})
const photos = store.collection<Photo>('photos')
const bytes = store.blobs.byteStore // a BlobStore
async function addPhoto(file: File, caption: string) {
const hash = await bytes.put(file, file.type) // 'sha256:<hex>'
await photos.set(crypto.randomUUID(), {
caption,
hash,
mime: file.type,
size: file.size,
})
}
const body = await bytes.get(hash) // Blob | null
put(data, mime?) returns a key made from the content hash, so the same bytes are stored once. BlobStore also has has, delete, list, getMeta and getRange.
A blob reference is an object with hash, mime and size. It can sit anywhere inside a document or collection record. Sync and garbage collection find blobs by looking for objects of that shape, so keep all three fields together.
store.blobs is a higher-level API that gives each file a stable id and a revision history (create, revise, delete, get, getHistory). See the blob spec.
Schema versions
Add a version entry when your data shape changes. Each entry after the first names the version it follows with from.
const store = new CloudStore({
id: 'app-k3m7q2x4p6w5z7n3b2v4c6h5',
storage: { db: new IDBStorage() },
documents: ['settings'],
collections: ['dishes'],
versions: [
{ version: '1.0.0', schema: v1Schema },
{
version: '2.0.0',
from: '1.0.0',
schema: v2Schema,
rename: { recipes: 'dishes' },
migrate: {
dishes: (data) => {
const dish = data as DishV1
return { ...dish, servings: dish.servings ?? 1 }
},
},
},
],
})
| Field | Notes |
|---|---|
version |
Semver string for this schema. |
schema |
JSON Schema for the whole store at this version. |
from |
The previous version. Omit on the first entry. |
rename |
Entity renames, { oldName: newName }. Runs during store.ready(). Both names must be the same kind. |
migrate |
Per-entity function (data, ctx) => data, keyed by the new name. May be async. ctx.store is the store. |
Migrations run on the client; the server does not know your schema. Older clients may still sync data in the old shape, so do not remove fields they write.
Storage backends
| Import | Records | Blobs | Runs in |
|---|---|---|---|
@civility/cloud/storage/idb |
IDBStorage |
IDBBlobStorage |
Browser (IndexedDB) |
@civility/cloud/storage/opfs |
none | OPFSBlobStorage |
Browser (OPFS) |
@civility/cloud/storage/memory |
MemoryStorage |
MemoryBlobStorage |
Anywhere; not saved |
@civility/cloud/storage/deno-fs |
DenoFsStorage |
DenoFSBlobStorage |
Deno (files) |
@civility/tauri |
TauriStorage |
TauriBlobStorage |
Tauri (files) |
With store id editor, IDBStorage uses the IndexedDB database editor and IDBBlobStorage uses editor-blobs. To write your own backend, implement StoreDatabase or BlobStorage from @civility/cloud.