Learn / Define an operation and check its laws
Give a checked function an operation name
Use Operation.derived when you already have an inspectable function built with Fn. Declare the result Schema on the function with .returns(schema). Use args to choose the positional order of its named parameters.
Pass one argument per declared slot when calling a primitive or derived operation.
import { Schema } from 'effect'
import { Expr, Num, Ord } from '@doeixd/metakit'
import * as Fn from '@doeixd/metakit/fn'
import * as Operation from '@doeixd/metakit/operation'
const debit = Fn.params({ balance: Schema.Int, amount: Schema.Int })
.where(({ balance, amount }) => Ord.gte(balance, amount))
.returns(Schema.Int)
.body(({ balance, amount }) => Num.sub(balance, amount))
const debitOp = Operation.derived({
id: 'ledger.debit',
definition: debit,
args: p => [p.balance, p.amount],
})
const foreign = Operation.implementations('ledger', debitOp.implementation)
const balance = Expr.eval(debitOp(100, 30), {}, { foreign })balance is 70. Evaluating debitOp(10, 30) refuses because the function's precondition fails. Both operation constructors propagate null arguments by default. To handle nulls in a derived function, use nulls: 'own' and give its parameters Schemas that accept null.
Use Operation.expandDerived(debitOp(100, 30), [debitOp]) to inline the body and its contract checks before translating the expression to SQL. Expansion keeps the named call if it cannot express a check or if the body ignores an argument that may refuse. To translate a retained call, supply a SQL lowering that implements the operation and its contracts.
Use it in folds and transitions
- Row folds:
Arr.reduce($.roles, flagsOr, each => each.bits)requirescommutative,associative, and a two-sidedidentityat compile time. - Commutative writes:
Transition.combine(state.flags, flagsOr, input.grant)letscommutesandidempotentfrom@doeixd/metakit/pairs, andfoldkit-syncreason about concurrent updates.
Lower to SQL
Keep SQL lowering out of browser bundles by importing @doeixd/metakit/operation/sql on the server only:
import { lowering, lowerings, piece } from '@doeixd/metakit/operation/sql'
export const sqlLowerings = lowerings(
lowering(flagsOr, {
sqlite: (a, b) => piece`(${a} | ${b})`,
postgres: (a, b) => piece`(${a} | ${b})`,
aggregate: { postgres: a => piece`bit_or(${a})` },
}),
)If a dialect lacks a lowering (such as SQLite's missing bit_or aggregate), @doeixd/metakit/sql refuses by operation name and dialect at compile/query time rather than silently falling back.
Next
- Group operations into a versioned domain language: Write your own language, store or protocol.
- Reference:
examples/metakit/src/permissions.ts.