Entity / Operators

A first named rule: listed

Suppose your catalog shows products once publishedAt is non-null across public queries, visitor guard rules, and reports. Declare listed once:

ts
import { Schema } from 'effect'
import { Collation, Entity, Expr, Query } from 'foldkit-entity'

const Product = Entity.define(
  'Product',
  Schema.Struct({
    id: Schema.String,
    upc: Schema.String,
    label: Schema.String,
    cents: Schema.Int,
    publishedAt: Schema.NullOr(Schema.String),
  }),
).pipe(Entity.annotateMembers({ upc: Collation.of(Collation.binary) }))
const { fields } = Product

const listed = Expr.operator('acme.listed', {
  input: [Schema.NullOr(Schema.String)],
  output: Schema.Boolean,
  definedAs: publishedAt => Expr.isNotNull(publishedAt),
})

const Listed = Query.from(Product).pipe(Query.where(listed(fields.publishedAt)))
Query.show(Listed)
// FROM Product
// WHERE acme.listed(Product.publishedAt)
Query.operators(Listed) // ['acme.listed']

What the calls mean

  • Expr.operator declares a pure value with a namespaced ID (acme.*; foldkit.* is reserved) and version (default 1).
  • definedAs builds an expression from its arguments once per call, so Listed compiles identically to Expr.isNotNull(fields.publishedAt) everywhere. Setting output: Schema.Boolean lets the operator appear inside and, or, not, guards, and invariants.
  • Argument isolation: A definedAs callback may read only its passed arguments (closing over external Entity fields throws so dependency tracking stays accurate).
  • Readable names: Query.show prints acme.listed(...) and Query.operators inspects operator usage across queries. (foldkit-cms ships Cms.published(entity) the same way.)