Classes
The Effect pages are for applications that already use Effect: see Schema-checked boxes.
Example
A model is a SchemaModel: a Schema.Class whose instances hold a realm
that its wire form never carries. A field whose name starts with $ is a
BoxField, or a CollectionField of rows by key
(Collection fields), and its wire key drops the $. A
field without $ is plain, readonly data. The class keeps check and
annotate, and seals extend, mapFields, makeOption, and makeEffect.
import { BoxField, computed, createRealm, SchemaModel, update } from "@frondruntime/pinna-effect";
import { Schema } from "effect";
const realm = createRealm();
class Todo extends SchemaModel<Todo>("Todo")({
id: Schema.String,
title: Schema.String,
$done: BoxField(Schema.Boolean), // a box field; the wire key is "done"
}) {
readonly $label = computed(this.realm, (read) =>
read(this.$done) ? `✓ ${this.title}` : this.title,
);
toggle(): void {
update(this.realm, (read, write) => {
write(this.$done, !read(this.$done));
});
}
}- A derived value is a
$property of the class body, made withcomputed(this.realm, ...). It is not a schema field, so it is not on the wire. - A method that writes calls
update(this.realm, ...).
decode(realm, Todo) makes instances from wire data. Every instance and
every box inside it belongs to the realm decode is given, the one made
above the class.
import { decode, untracked } from "@frondruntime/pinna-effect";
// Throws the SchemaError when the input does not fit.
const todo = decode(realm, Todo)({ id: "1", title: "Write the docs", done: false });
todo.toggle();
const label = untracked(realm, (read) => read(todo.$label)); // "✓ Write the docs"A FromContext field holds a value of the caller’s own, such as a
formatter or a client: the service of an Effect Context.Service tag.
decode takes it from the Context it is given; it is never on the wire.
import { BoxField, computed, decode, FromContext, SchemaModel } from "@frondruntime/pinna-effect";
import { Context, Schema } from "effect";
interface MoneyFormat {
readonly format: (amount: number) => string;
}
// An Effect service: the field requires it, and the caller provides it.
class Money extends Context.Service<Money, MoneyFormat>()("app/Money") {}
class Price extends SchemaModel<Price>("Price")({
$amount: BoxField(Schema.Number),
money: FromContext(Money), // the caller's own value, never on the wire
}) {
readonly $label = computed(this.realm, (read) => this.money.format(read(this.$amount)));
}
const euros: MoneyFormat = { format: (amount) => `€${amount.toFixed(2)}` };
const price = decode(realm, Price, Context.make(Money, euros))({ amount: 12 });An Effect program decodes the same class with Schema.decodeUnknownEffect.
The tag is one of its requirements, provided as any service is, with
Effect.provideService or a Layer. The realm comes from RealmService, as
for every Effect program.
import { RealmService } from "@frondruntime/pinna-effect";
import { Effect, Schema } from "effect";
// Money is a requirement like any service: Effect<Price, SchemaError, Money | RealmService>.
const loadPrice = (json: unknown) => Schema.decodeUnknownEffect(Price)(json);
const loaded = Effect.runSync(
loadPrice({ amount: 12 }).pipe(
Effect.provideService(Money, euros),
Effect.provideService(RealmService, realm),
),
);Rules
- Make instances with
decode(realm, Todo)(json). Every instance has arealmfield, never on the wire:decodefills it, and field initializers usethis.realm. Todo.make({ id, title, done: false, realm })builds an instance from values already in hand. It takes each$field’s starting value under its wire key, and builds the box in the instance’s realm. A box under the$key throwspinna: Todo.make takes the value of $done under "done", never a box under "$done", so a spread instance never shares its box with the new one.makechecks each$field’s value even under{ disableChecks: true }, which skips only the plain fields’ checks: the box checks every value it holds, its first included.- A model in another schema’s
makeis an instance. A plain object in its place throwspinna: a Todo field of another schema takes an instance; build it with Todo.make or decode, because its boxes would be another instance’s, or none. - A field list that breaks a naming rule makes
SchemaModelthrow when the class is defined, so no instance is ever half-declared:- two fields with one wire key, such as
$countandcount:pinna: Counter.$count and Counter.count both read "count"; rename one; - a field whose wire key is
realm:pinna: Counter.realm reads "realm", the realm the instance belongs to; rename the field; - a
$field that is not aBoxFieldor aCollectionField:pinna: Counter.$count is named as a box; declare it BoxField(...) or CollectionField(...); - a
BoxFieldor aCollectionFieldwithout$:pinna: Counter.count holds a box; name it $count.
- two fields with one wire key, such as
BoxFieldandCollectionFieldare fields of aSchemaModelonly. In any other schema they fail to decode and encode withpinna: BoxField is a SchemaModel field; declare it in SchemaModel(...), never in another schema(orCollectionField), because the$key would go on the wire.extend,mapFields,makeOption, andmakeEffectthrow and do not compile on aSchemaModel: the first two would declare fields without its checks, and the last two would take boxes wheremaketakes values. The call throwspinna: Todo.extend is not supported; declare another SchemaModel with every field it needs, and the same formapFields;makeOptionandmakeEffectthrowpinna: Todo.makeOption is not supported; call make, which throws the schema error, or decode.- A plain getter has no
readto call, and a method that takesreadis not cached. A value several components need is a computed field. - A context field’s tag is a requirement of the decode, at any depth:
decodewithout aContextholding the tag does not compile, and neither does running aSchema.decodeUnknownEffectthat nothing provides it to. AContextholding more tags compiles. A schema with no context field takes noContext.Schema.decodeUnknownSyncdoes not compile on such a schema, because it runs without services. - The
Contextgiven todecodemay hold any Effect service, such as aClock, and the schema’s own transformations read them from Effect. - A field reads its tag from the Effect context, so the innermost provider
wins, as for any service: an Effect decode inside a
decode’s transformation that provides a tag the outerdecodealso holds reads its own value. - Plain fields are never written after
decode. A value that changes is a$field. - Encoding an instance, as
Schema.encodeSync(Todo)(todo), gives the schema’s wire fields and nothing else, each$field’s current value under its wire key. Therealm, aFromContextfield, computed fields, and other instance properties stay off the wire, so what is sent is the schema’s encoded form. - Declare a class with no
$field as a plainSchema.Class. ASchemaModelwithout one still has arealmfield, so decoding it needs a realm, andRealmServicein an Effect program, for nothing to observe.
Answers
| Call | Answers |
|---|---|
SchemaModel<Self>(identifier)(fields) |
A class whose $ fields are boxes or collections, checked by its schema. |
BoxField(schema) |
A field that is a box of schema, under the wire key without the $. |
CollectionField(rowSchema, { keyOf }) |
A field that is a collection of rows by key, each row checked against rowSchema and compared with its equivalence: see Collection fields. |
decode(realm, schema, context?)(input) |
The decoded value, or throws Schema.SchemaError. |
FromContext(tag) |
A field holding the service of tag, never on the wire, that puts tag in the schema’s requirements. |
Todo.make({ ...values, realm }) |
An instance from values in hand, each $ field’s value under its wire key. |
See also
- Schema-checked boxes: what a
$field checks on a write. - Errors: the path and message of each field
decoderefuses. - Collection fields: rows by key, as a
$field. - Boxes and computed: what a
$field and a computed field are. - Updates: what a write checks, and when it is undone.
- Hooks: reading a model in a component.
- Equality and hashing: when two instances of a model are equal, and a class’s own
Equal. - Coming from MobX: a MobX store as a
SchemaModel.