Sync / Editing server data
A first editable column: cents
Three helpers implement this loop: EditableEntity (foldkit-sync/entity) tracks per-cell edits, RemoteEdits (foldkit-sync/remote) projects them onto Remote rows, and editsJournal (foldkit-sync/journal) settles and compacts them on the server.
Start in your shared domain module by declaring which entity fields accept cell edits:
import { EditableEntity } from 'foldkit-sync/entity'
const Product = Entity.define('Product', Schema.Struct({ id: Schema.String, cents: Schema.Number }))
export const ProductEdits = EditableEntity.make(Product, { members: ['cents'] })Next, add the edits slice and EditedProducts durable Message to your application bundle, merge incoming edits in update, and reconcile Remote overlays in Sync.mount's afterUpdate:
import { RemoteEdits } from 'foldkit-sync/remote'
const Base = Bundle.compose({
remote: Remote.Model,
edits: Schema.Array(ProductEdits.Edit),
}).pipe(Bundle.withMessages({ ...Remote.messages, EditedProducts: ProductEdits.edited }))
type EditedMsg = { readonly _tag: 'EditedProducts' } & Schema.Schema.Type<
Schema.Struct<typeof ProductEdits.edited>
>
const foldEdited = (model: Model, { changes, at, by }: EditedMsg) => ({
model: modifyFields(model, {
edits: (edits: ReadonlyArray<typeof ProductEdits.Edit.Type>) =>
ProductEdits.merge(edits, changes, Option.fromUndefinedOr(at), Option.fromUndefinedOr(by)),
}),
})
const Made = Surface.application({
Model: ProductSchema,
Message: Base.Message,
initial: { remote: Remote.initial, edits: [] },
update: (model: Model) => ({ model }),
})
const Data = Remote.make({ model: Made.model.remote, entities: [Product], queries: [] })
const Shown = RemoteEdits.make(Data, ProductEdits)
// Run in Sync.mount's afterUpdate hook (never during replay)
const afterUpdate = (model: Model) => ({
model: Shown.reconcile(model, model.edits, replica.replicaId).model,
})On your Sync contract, attach the server stamp when EditedProducts commits:
const stampEdited = ({ changes }: EditedMsg, commit: CommitStamp) => ({
changes,
...ProductEdits.stamped(commit),
})On the server, wire editsJournal to apply settled edits to your Drizzle binding (applyEdits) and compact absorbed history (with your journal, database, ProductBinding, sqlite, editsOf, and absorbed handlers):
import { editsJournal } from 'foldkit-sync/journal'
const applyProduct = applyEdits(ProductBinding)
const { settle, absorb } = editsJournal({
documentId: 'registry-edits',
journal,
editsOf,
apply: (change, at) => applyProduct(change, at).pipe(Effect.provide(database)),
tableRevision: Effect.try(() => sqlite.highestRevision()),
holdsThrough: (snapshot, through) => ProductEdits.holdsThrough(snapshot.edits, through),
absorbed,
server: 'server',
})Run settle on every journal exchange (via journalExchange) and call absorb on a schedule. See examples/registry/src/journal.ts for the full editsOf and absorbed implementations.