The best way to control Claude Code, Codex and more from any computer or phone

main
md 85 lines 2.63 KB
Rendered Raw
1 # @alchemy.run/domain
2
3 A domain-driven design framework for [Effect](https://effect.website), part of [Alchemy](https://alchemy.run). Model your business as commands, aggregates, events, views, and policies. Test it in memory, then run it on Cloudflare Durable Objects without changing the model.
4
5 ```sh
6 npm install @alchemy.run/domain effect
7 ```
8
9 Commands ask for a change, the aggregate decides it, and events record what happened:
10
11 ```typescript
12 // src/account.ts
13 import * as Domain from "@alchemy.run/domain";
14 import * as Schema from "effect/Schema";
15
16 export class MoneyDeposited extends Domain.Event("MoneyDeposited", {
17 amount: Schema.Int,
18 balanceAfter: Schema.Int,
19 }) {}
20
21 export class TooLarge extends Domain.Rejection("TooLarge", { max: Schema.Int }) {}
22
23 export class DepositMoney extends Domain.Command("DepositMoney", {
24 target: Schema.String,
25 input: { amount: Schema.Int },
26 events: [MoneyDeposited],
27 rejects: [TooLarge],
28 reply: { balance: Schema.Int },
29 }) {}
30
31 export class Account extends Domain.Aggregate("Account", {
32 id: Schema.String,
33 state: Schema.Struct({ balance: Schema.Int }),
34 initial: { balance: 0 },
35 commands: [DepositMoney],
36 decide: {
37 DepositMoney: (s, cmd) =>
38 cmd.amount > 10_000
39 ? new TooLarge({ max: 10_000 })
40 : [new MoneyDeposited({ amount: cmd.amount, balanceAfter: s.balance + cmd.amount })],
41 },
42 evolve: {
43 MoneyDeposited: (s, e) => ({ balance: e.balanceAfter }),
44 },
45 reply: {
46 DepositMoney: (s) => ({ balance: s.balance }),
47 },
48 }) {}
49
50 export class Bank extends Domain.Model("Bank", { aggregates: [Account] }) {}
51 ```
52
53 Behaviour is tested as a story: given these events, when this command, then these events:
54
55 ```typescript
56 // test/account.test.ts
57 import { Story } from "@alchemy.run/domain/Story";
58 import { it } from "@effect/vitest";
59 import { Account, Bank, DepositMoney, MoneyDeposited, TooLarge } from "../src/account.ts";
60
61 const story = Story.make(Bank, {});
62 const account = Account.ref("a-1");
63
64 it.effect("deposits and replies with the balance", () =>
65 story(
66 Story.given(account, new MoneyDeposited({ amount: 50, balanceAfter: 50 })),
67 Story.when(account, new DepositMoney({ amount: 100 })),
68 Story.then(account, new MoneyDeposited({ amount: 100, balanceAfter: 150 })),
69 Story.replied({ balance: 150 }),
70 ),
71 );
72
73 it.effect("rejects large deposits", () =>
74 story(
75 Story.when(account, new DepositMoney({ amount: 20_000 })),
76 Story.rejected(new TooLarge({ max: 10_000 })),
77 ),
78 );
79 ```
80
81 ## Learn more
82
83 - [Domain on alchemy.run](https://alchemy.run/domain)
84 - [Tutorial](https://alchemy.run/domain/tutorial/part-1)
85 - [Running on Cloudflare](https://alchemy.run/domain/cloudflare)