Remote / Declared writes

A first precondition: publishing a draft

Suppose a Product can only be published when its status is 'draft'. Declare the entity, a Publish write, and a Sell stock-adjustment write once, then serve Publish without writing a custom SQL handler:

ts
import { Schema } from 'effect'
import { Entity, Expr, Write } from 'foldkit-entity'
import { Mutation } from 'foldkit-remote'

const Product = Entity.define(
  'Product',
  Schema.Struct({
    id: Schema.String,
    name: Schema.String,
    status: Schema.Literals(['draft', 'published', 'archived']),
    stock: Schema.Number,
    revision: Schema.Number,
  }),
)

const Publish = Mutation.write(
  'Publish',
  Write.update(
    Entity.input(Product, Schema.Struct({ id: Schema.String, status: Schema.Literal('published') })),
    { id: 'id', when: () => Expr.eq(Product.fields.status, 'draft') },
  ),
)

const Sell = Mutation.write(
  'Sell',
  Write.update(
    Entity.input(Product, Schema.Struct({ id: Schema.String, quantity: Schema.Int }), {
      quantity: Entity.unmapped,
    }),
    { id: 'id', increment: { stock: 'quantity' } },
  ),
)

Serve Publish directly with writer(Db.Product):

ts
import { sqliteTable, text, integer } from 'drizzle-orm/sqlite-core'
import { bind, writer } from 'foldkit-remote-drizzle'
import { RemoteServer } from 'foldkit-remote-server'

const products = sqliteTable('products', {
  id: text('id').primaryKey(),
  name: text('name').notNull(),
  status: text('status').notNull(),
  stock: integer('stock').notNull(),
  revision: integer('revision').notNull(),
})
const Db = bind({ Product }, { Product: { table: products } })

const server = RemoteServer.make({
  entities: [],
  mutations: [RemoteServer.write(Publish, writer(Db.Product))],
})

A draft product transitions to 'published'; an archived product is refused with Unmet; an already published product returns cleanly without altering the row.

What each call does:

  • Write.update(input, { id, when }) defines the update declaration and compiles when against the Entity's own fields.
  • Schema.Literal('published') pins a constant value in the input schema so decoders reject any other status before reaching the writer.
  • Mutation.write types the mutation's exact refusal union (Unmet and Conflict for guarded/preconditioned updates; Taken for inserts).
  • writer(Db.Product) executes the single SQL UPDATE and classifies failures when zero rows match.