v0 · Developer PreviewSorus is under active development. APIs may change between releases.

Schema-checked boxes

Example

Box.schema, from @frondruntime/sorus-effect, makes a box that checks an Effect Schema on every write. The composer’s text holds at most 2,000 characters.

ts
import { Box } from "@frondruntime/sorus-effect";
import { Schema } from "effect";
import { app } from "./realm.ts";

const Composer = Schema.Struct({
  text: Schema.String.check(Schema.isMaxLength(2000)),
  replyTo: Schema.NullOr(Schema.String),
});

const $composer = Box.schema(app, Composer, { text: "", replyTo: null }, { name: "composer" });
const $mentions = Box.schema(app, Schema.Array(Schema.String), [], { name: "mentions" });

Collection.schema checks each row as it lands, after Model.decode has checked the wire data.

ts
import { Collection, Model, Realm } from "@frondruntime/sorus-effect";
import { Schema } from "effect";
import { app } from "./realm.ts";

const MessageData = Schema.Struct({
  id: Schema.String,
  roomId: Schema.String,
  author: Schema.String,
  text: Schema.String.check(Schema.isMaxLength(2000)),
  sentAt: Schema.Number,
});

// Each row is checked as it lands: an upsert of a message over 2,000
// characters throws and undoes its update.
const $messages = Collection.schema(app, MessageData, {
  keyOf: (message) => message.id,
  name: "messages",
});

const receive = (json: unknown) => {
  // decode checks the wire data; upsert checks the row again as it lands.
  const message = Model.decode(app, MessageData)(json);
  Realm.update(app, (_read, write) => {
    write.upsert($messages, message, { at: "end" });
  });
};

Rules

  • A write or an initial the schema rejects throws ValueRejectedError and undoes the update, so no box holds a rejected value. No option turns the check off; a plain Box.make checks nothing.
  • A schema box compares as Equality and hashing lists, so an equal array or object notifies nobody.
  • A box of a plain Schema.Array(element) checks only the elements a write put there; any other box checks its whole value on every write. A list written one row at a time is a collection field.
  • A check runs when a value is written, never on a read or a recompute, so it holds only what the value decides: terms that must agree are one schema value with one check.

Answers

Call Answers
Box.schema(realm, schema, initial, { name?, equals? }) A box of the values schema accepts. Throws ValueRejectedError when initial does not fit.
Collection.schema(realm, schema, { keyOf, name?, equals? }) A collection whose rows schema accepts, each checked as it lands.

See also