A model is a Schema.Class.
class.test.tsSchemaModelis an EffectSchema.Classwhose$fields hold state: aBoxFieldis a box, aCollectionFieldholds rows by key. Plain fields stay plain.Every write is checked.
A write the field's schema refuses throws to the caller, with the
box.test.tsSchema.SchemaErroras its cause, and the wholeupdateis undone.The wire is the schema.
mix.test.tsdecodetakes JSON to a model in a realm and throwsSchema.SchemaErroron input that does not fit;Schema.encodeSynctakes the model back to JSON with the boxes' current values.
import {
BoxField,
CollectionField,
computed,
createRealm,
decode,
SchemaModel,
update,
} from "@frondruntime/pinna-effect";
import { Schema } from "effect";
// A line holds a plain field, and a box field whose schema checks every write.
class Line extends SchemaModel<Line>("Line")({
sku: Schema.String,
$quantity: BoxField(Schema.Int.check(Schema.isGreaterThan(0))),
}) {}
// An order holds its lines by key, and derives the units from them.
class Order extends SchemaModel<Order>("Order")({
id: Schema.String,
$lines: CollectionField(Line, { keyOf: (line) => line.sku }),
}) {
readonly $units = computed(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 {
update(this.realm, (read, write) => {
const line = read.row(this.$lines, sku);
if (line !== undefined) write(line.$quantity, quantity);
});
}
}
const realm = createRealm();
// JSON in, a checked Order out; input that does not fit throws a Schema.SchemaError.
const order = decode(realm, Order)({ id: "7", lines: [{ sku: "pen", quantity: 2 }] });
Schema.encodeSync(Order)(order); // { id: "7", lines: [{ sku: "pen", quantity: 2 }] }