Domain.Projection reference
Projection
Section titled “Projection”Source:
packages/domain/src/Projection.ts
Consumes events into a store you own: a database, a search index, a
warehouse, or a Domain.Stream. Inputs are routed to keys and handled in
order per key, at least once, and batched if its Layer says so. A projection
never sends commands: replaying it must never act on the world again.
The declaration holds what it means (sources, partitioning, events, the streams it writes). Its Layer holds how it runs: the handler, and options such as batching.
Projection: Writing to a database
Section titled “Projection: Writing to a database”import * as Domain from "@alchemy.run/domain";import * as Effect from "effect/Effect";import { Account } from "./Account.ts";import { MoneyDeposited } from "./DepositMoney.ts";import { LedgerStore } from "./LedgerStore.ts";
export class Ledger extends Domain.Projection("Ledger", { from: [Account], key: Account, on: [MoneyDeposited],}) {}
export const LedgerLive = Ledger.toLayer( Effect.gen(function* () { const store = yield* LedgerStore; return Effect.fn(function* (batch) { yield* store.upsert( batch.map(({ key, event, envelope }) => ({ id: `${envelope.stream}:${envelope.seq}`, account: key.id, amount: event.amount, })), ); }); }), { batch: { size: 500, wait: "2 seconds" } },);Projection: Following a rewrite
Section titled “Projection: Following a rewrite”A Domain.Rewrite changes events a projection may already have written.
Return write and rewrite from the Layer: write is the handler, and
rewrite is given each such event as it was and as it is now, in order
with the key’s other inputs.
export const DirectoryLive = Directory.toLayer( Effect.gen(function* () { const store = yield* DirectoryStore; return { write: Effect.fn(function* (batch) { yield* store.put(batch.map(({ key, event }) => ({ id: key.id, name: event.name }))); }), rewrite: Effect.fn(function* (batch) { for (const { key, after } of batch) { if (after === undefined) yield* store.remove(key.id); else yield* store.put([{ id: key.id, name: after.name }]); } }), }; }),);Projection: Reading your own write
Section titled “Projection: Reading your own write”const receipt = yield* accounts.send(new DepositMoney({ accountId, amount: 100 }));yield* Ledger.caughtUp(receipt);Projection: Annotating projections
Section titled “Projection: Annotating projections”The last argument is its annotations: data for what is built on the
model, read back as X.annotations. Add your own keys by augmenting
Domain.Annotations.
Nothing a client calls shows it; it is for the people and the tools that
read the model, as X.annotations.
export class Ledger extends Domain.Projection( "Ledger", { from: [Account], key: Account, on: [MoneyDeposited, MoneyWithdrawn] }, { description: "Every money movement on an account, oldest first." },) {}