A model is a Schema.Class.
class.test.tsModel.Schemais an EffectSchema.Classwhose$fields hold state: aModel.boxFieldis a box, aModel.collectionFieldholds rows by key. Plain fields stay plain.Every write is checked.
A write the field's schema refuses throws
box.test.tsValueRejectedErrorto the caller, with theSchema.SchemaErroras its cause, and the wholeRealm.updateis undone.The wire is the schema.
mix.test.tsModel.decodetakes JSON to a model in a realm and throwsDecodeError, whose cause is theSchema.SchemaError, on input that does not fit;Schema.encodeSynctakes the model back to JSON with the boxes' current values.
import { Computed, Model, Realm } from "@frondruntime/sorus-effect";
import { Schema } from "effect";
// A line holds a plain field, and a box field whose schema checks every write.
class Line extends Model.Schema<Line>("Line")({
sku: Schema.String,
$quantity: Model.boxField(Schema.Int.check(Schema.isGreaterThan(0))),
}) {}
// An order holds its lines by key, and derives the units from them.
class Order extends Model.Schema<Order>("Order")({
id: Schema.String,
$lines: Model.collectionField(Line, { keyOf: (line) => line.sku }),
}) {
readonly $units = Computed.make(this.realm, (read) =>
read(this.$lines.rows).reduce((units, line) => units + read(line.$quantity), 0),
);
// A quantity the schema refuses, such as 0, throws to the caller with the
// Schema.SchemaError as its cause, and the update is undone.
setQuantity(sku: string, quantity: number): void {
Realm.update(this.realm, (read, write) => {
const line = read.row(this.$lines, sku);
if (line !== undefined) write(line.$quantity, quantity);
});
}
}
const realm = Realm.make();
// JSON in, a checked Order out; input that does not fit throws a DecodeError.
const order = Model.decode(realm, Order)({ id: "7", lines: [{ sku: "pen", quantity: 2 }] });
Schema.encodeSync(Order)(order); // { id: "7", lines: [{ sku: "pen", quantity: 2 }] }