The best way to control Claude Code, Codex and more from any computer or phone
| 1 | --- |
| 2 | title: "Part 4: Expose an Api" |
| 3 | description: Authenticate requests, let customers act only on their own accounts, and expose the bank through a typed Api. |
| 4 | sidebar: |
| 5 | order: 4 |
| 6 | --- |
| 7 | |
| 8 | Customers will reach the bank from outside. Give every request a signed-in customer, check ownership on every command and read, and expose the bank through an Api. |
| 9 | |
| 10 | ## Know who is asking |
| 11 | |
| 12 | ```typescript |
| 13 | // src/CurrentActor.context.ts |
| 14 | import * as Domain from "@alchemy.run/domain"; |
| 15 | import * as Schema from "effect/Schema"; |
| 16 | import { CustomerId } from "./Customer.id.ts"; |
| 17 | |
| 18 | export class CurrentActor extends Domain.RequestContext<CurrentActor>()( |
| 19 | "Bank/CurrentActor", |
| 20 | Schema.Struct({ customerId: CustomerId }), |
| 21 | ) {} |
| 22 | ``` |
| 23 | |
| 24 | `CurrentActor` is the customer behind a request. It has a schema because it travels with each command to the account that decides it. |
| 25 | |
| 26 | ## Authenticate requests |
| 27 | |
| 28 | ```typescript |
| 29 | // src/Session.middleware.ts |
| 30 | import * as Effect from "effect/Effect"; |
| 31 | import * as Headers from "effect/http/Headers"; |
| 32 | import * as Layer from "effect/Layer"; |
| 33 | import * as Option from "effect/Option"; |
| 34 | import * as RpcMiddleware from "effect/rpc/RpcMiddleware"; |
| 35 | import * as Schema from "effect/Schema"; |
| 36 | import { CurrentActor } from "./CurrentActor.context.ts"; |
| 37 | import { CustomerId } from "./Customer.id.ts"; |
| 38 | |
| 39 | export class Unauthorized extends Schema.TaggedError<Unauthorized>()("Unauthorized", {}) {} |
| 40 | |
| 41 | export class Session extends RpcMiddleware.Service<Session, { provides: CurrentActor }>()( |
| 42 | "Bank/Session", |
| 43 | { error: Unauthorized }, |
| 44 | ) {} |
| 45 | |
| 46 | // Demo only: trusts `Authorization: Bearer <customer id>`. Verify a real session in production. |
| 47 | export const SessionLive = Layer.succeed(Session, (effect, { headers }) => |
| 48 | Option.match(Headers.get(headers, "authorization"), { |
| 49 | onNone: () => Effect.fail(new Unauthorized()), |
| 50 | onSome: (value) => |
| 51 | value.startsWith("Bearer ") |
| 52 | ? Effect.provideService(effect, CurrentActor, { |
| 53 | customerId: CustomerId.make(value.slice("Bearer ".length)), |
| 54 | }) |
| 55 | : Effect.fail(new Unauthorized()), |
| 56 | }), |
| 57 | ); |
| 58 | |
| 59 | export const sessionClient = (customerId: string) => |
| 60 | RpcMiddleware.layerClient(Session, ({ request, next }) => |
| 61 | next({ ...request, headers: Headers.set(request.headers, "authorization", `Bearer ${customerId}`) }), |
| 62 | ); |
| 63 | ``` |
| 64 | |
| 65 | `Session` is middleware: it runs before a command or read and provides `CurrentActor`. `SessionLive` is the server side, and `sessionClient` attaches the header from a client. [Part 6](/domain/tutorial/part-6) replaces the header with a browser cookie. |
| 66 | |
| 67 | ## Refuse someone else's account |
| 68 | |
| 69 | ```typescript |
| 70 | // src/NotOwner.rejection.ts |
| 71 | import * as Domain from "@alchemy.run/domain"; |
| 72 | |
| 73 | export class NotOwner extends Domain.Rejection("NotOwner") {} |
| 74 | ``` |
| 75 | |
| 76 | `NotOwner` is the answer for someone else's account. Deposits and withdrawals both return it, so it gets its own file. |
| 77 | |
| 78 | ## Guard deposits and withdrawals |
| 79 | |
| 80 | ```diff lang="typescript" |
| 81 | // src/DepositMoney.command.ts |
| 82 | import { AccountId } from "./Account.id.ts"; |
| 83 | import { NotOpen } from "./NotOpen.rejection.ts"; |
| 84 | +import { NotOwner } from "./NotOwner.rejection.ts"; |
| 85 | +import { Session } from "./Session.middleware.ts"; |
| 86 | |
| 87 | export class MoneyDeposited extends Domain.Event("MoneyDeposited", { |
| 88 | // ... |
| 89 | }) {} |
| 90 | |
| 91 | export class DepositMoney extends Domain.Command("DepositMoney", { |
| 92 | target: AccountId, |
| 93 | + middleware: [Session], |
| 94 | input: { amount: Schema.Int }, |
| 95 | events: [MoneyDeposited], |
| 96 | - rejects: [NotOpen], |
| 97 | + rejects: [NotOpen, NotOwner], |
| 98 | reply: { balance: Schema.Int }, |
| 99 | }) {} |
| 100 | ``` |
| 101 | |
| 102 | ```diff lang="typescript" |
| 103 | // src/WithdrawMoney.command.ts |
| 104 | import { AccountId } from "./Account.id.ts"; |
| 105 | import { NotOpen } from "./NotOpen.rejection.ts"; |
| 106 | +import { NotOwner } from "./NotOwner.rejection.ts"; |
| 107 | +import { Session } from "./Session.middleware.ts"; |
| 108 | |
| 109 | export class MoneyWithdrawn extends Domain.Event("MoneyWithdrawn", { |
| 110 | // ... |
| 111 | }) {} |
| 112 | |
| 113 | export class WithdrawMoney extends Domain.Command("WithdrawMoney", { |
| 114 | target: AccountId, |
| 115 | + middleware: [Session], |
| 116 | input: { amount: Schema.Int }, |
| 117 | events: [MoneyWithdrawn], |
| 118 | - rejects: [NotOpen, InsufficientFunds], |
| 119 | + rejects: [NotOpen, NotOwner, InsufficientFunds], |
| 120 | reply: { balance: Schema.Int }, |
| 121 | }) {} |
| 122 | ``` |
| 123 | |
| 124 | Each command lists its middleware, here `Session`, and every way it can fail. Both change the same way, each in its own file. |
| 125 | |
| 126 | ## Check the owner |
| 127 | |
| 128 | ```diff lang="typescript" |
| 129 | // src/Account.aggregate.ts |
| 130 | import * as Domain from "@alchemy.run/domain"; |
| 131 | +import * as Effect from "effect/Effect"; |
| 132 | import * as Schema from "effect/Schema"; |
| 133 | import { AccountId } from "./Account.id.ts"; |
| 134 | +import { CurrentActor } from "./CurrentActor.context.ts"; |
| 135 | import { DepositMoney, MoneyDeposited } from "./DepositMoney.command.ts"; |
| 136 | import { NotOpen } from "./NotOpen.rejection.ts"; |
| 137 | +import { NotOwner } from "./NotOwner.rejection.ts"; |
| 138 | import { AccountOpened, AlreadyOpen, OpenAccount } from "./OpenAccount.command.ts"; |
| 139 | import { InsufficientFunds, MoneyWithdrawn, WithdrawMoney } from "./WithdrawMoney.command.ts"; |
| 140 | // ... |
| 141 | ]); |
| 142 | type State = typeof State.Type; |
| 143 | + |
| 144 | +// The open account, if the current customer owns it. |
| 145 | +const owned = Effect.fn(function* (s: State) { |
| 146 | + if (s._tag !== "Open") return yield* new NotOpen(); |
| 147 | + const actor = yield* CurrentActor; |
| 148 | + if (actor.customerId !== s.owner) return yield* new NotOwner(); |
| 149 | + return s; |
| 150 | +}); |
| 151 | // ... |
| 152 | OpenAccount: (s, cmd) => |
| 153 | s._tag !== "Unopened" ? new AlreadyOpen() : [new AccountOpened({ owner: cmd.owner })], |
| 154 | - DepositMoney: (s, cmd) => |
| 155 | - s._tag !== "Open" |
| 156 | - ? new NotOpen() |
| 157 | - : [new MoneyDeposited({ amount: cmd.amount, balanceAfter: s.balance + cmd.amount })], |
| 158 | - WithdrawMoney: (s, cmd) => |
| 159 | - s._tag !== "Open" |
| 160 | - ? new NotOpen() |
| 161 | - : cmd.amount > s.balance |
| 162 | - ? new InsufficientFunds({ balance: s.balance, requested: cmd.amount }) |
| 163 | - : [new MoneyWithdrawn({ amount: cmd.amount, balanceAfter: s.balance - cmd.amount })], |
| 164 | + DepositMoney: Effect.fn(function* (s, cmd) { |
| 165 | + const open = yield* owned(s); |
| 166 | + return [new MoneyDeposited({ amount: cmd.amount, balanceAfter: open.balance + cmd.amount })]; |
| 167 | + }), |
| 168 | + WithdrawMoney: Effect.fn(function* (s, cmd) { |
| 169 | + const open = yield* owned(s); |
| 170 | + if (cmd.amount > open.balance) { |
| 171 | + return yield* new InsufficientFunds({ balance: open.balance, requested: cmd.amount }); |
| 172 | + } |
| 173 | + return [new MoneyWithdrawn({ amount: cmd.amount, balanceAfter: open.balance - cmd.amount })]; |
| 174 | + }), |
| 175 | }, |
| 176 | evolve: { |
| 177 | ``` |
| 178 | |
| 179 | `decide` can be an `Effect.fn` that reads what the middleware provides. `owned` checks the account is open and belongs to the customer asking. `OpenAccount` has no middleware: only the policy sends it. |
| 180 | |
| 181 | ## Refuse to register someone else |
| 182 | |
| 183 | ```diff lang="typescript" |
| 184 | // src/RegisterCustomer.command.ts |
| 185 | import * as Schema from "effect/Schema"; |
| 186 | import { CustomerId } from "./Customer.id.ts"; |
| 187 | +import { Session } from "./Session.middleware.ts"; |
| 188 | |
| 189 | export class CustomerRegistered extends Domain.Event("CustomerRegistered", { |
| 190 | // ... |
| 191 | }) {} |
| 192 | |
| 193 | export class AlreadyRegistered extends Domain.Rejection("AlreadyRegistered") {} |
| 194 | |
| 195 | +export class NotYou extends Domain.Rejection("NotYou") {} |
| 196 | + |
| 197 | export class RegisterCustomer extends Domain.Command("RegisterCustomer", { |
| 198 | target: CustomerId, |
| 199 | + middleware: [Session], |
| 200 | input: { name: Schema.String }, |
| 201 | events: [CustomerRegistered], |
| 202 | - rejects: [AlreadyRegistered], |
| 203 | + rejects: [AlreadyRegistered, NotYou], |
| 204 | }) {} |
| 205 | ``` |
| 206 | |
| 207 | `RegisterCustomer` now needs a session, and can refuse with `NotYou`, which only it returns. |
| 208 | |
| 209 | ## Register only yourself |
| 210 | |
| 211 | ```diff lang="typescript" |
| 212 | // src/Customer.aggregate.ts |
| 213 | import * as Domain from "@alchemy.run/domain"; |
| 214 | +import * as Effect from "effect/Effect"; |
| 215 | import * as Schema from "effect/Schema"; |
| 216 | +import { CurrentActor } from "./CurrentActor.context.ts"; |
| 217 | import { CustomerId } from "./Customer.id.ts"; |
| 218 | -import { AlreadyRegistered, CustomerRegistered, RegisterCustomer } from "./RegisterCustomer.command.ts"; |
| 219 | +import { |
| 220 | + AlreadyRegistered, |
| 221 | + CustomerRegistered, |
| 222 | + NotYou, |
| 223 | + RegisterCustomer, |
| 224 | +} from "./RegisterCustomer.command.ts"; |
| 225 | |
| 226 | export class Customer extends Domain.Aggregate("Customer", { |
| 227 | // ... |
| 228 | commands: [RegisterCustomer], |
| 229 | decide: { |
| 230 | - RegisterCustomer: (s, cmd) => |
| 231 | - s.name !== null ? new AlreadyRegistered() : [new CustomerRegistered({ name: cmd.name })], |
| 232 | + RegisterCustomer: Effect.fn(function* (s, cmd, { id }) { |
| 233 | + const actor = yield* CurrentActor; |
| 234 | + if (actor.customerId !== id) return yield* new NotYou(); |
| 235 | + if (s.name !== null) return yield* new AlreadyRegistered(); |
| 236 | + return [new CustomerRegistered({ name: cmd.name })]; |
| 237 | + }), |
| 238 | }, |
| 239 | evolve: { |
| 240 | ``` |
| 241 | |
| 242 | The third argument to `decide` holds the id of the customer being registered, so a customer can register only themselves. |
| 243 | |
| 244 | ## Let only the owner read the summary |
| 245 | |
| 246 | ```diff lang="typescript" |
| 247 | // src/AccountSummary.view.ts |
| 248 | import * as Domain from "@alchemy.run/domain"; |
| 249 | +import * as Effect from "effect/Effect"; |
| 250 | import * as Schema from "effect/Schema"; |
| 251 | import { Account } from "./Account.aggregate.ts"; |
| 252 | +import { CurrentActor } from "./CurrentActor.context.ts"; |
| 253 | +import { NotOwner } from "./NotOwner.rejection.ts"; |
| 254 | +import { Session } from "./Session.middleware.ts"; |
| 255 | |
| 256 | export class AccountSummary extends Domain.View("AccountSummary", { |
| 257 | from: [Account], |
| 258 | key: Account, |
| 259 | + middleware: [Session], |
| 260 | + rejects: [NotOwner], |
| 261 | state: Schema.Struct({ owner: Schema.NullOr(Schema.String), balance: Schema.Int }), |
| 262 | initial: { owner: null, balance: 0 }, |
| 263 | // ... |
| 264 | MoneyWithdrawn: (v, e) => ({ ...v, balance: e.balanceAfter }), |
| 265 | }, |
| 266 | + validate: Effect.fn(function* (_request, summary) { |
| 267 | + const actor = yield* CurrentActor; |
| 268 | + if (summary?.owner && summary.owner !== actor.customerId) return yield* new NotOwner(); |
| 269 | + }), |
| 270 | }) {} |
| 271 | ``` |
| 272 | |
| 273 | A view guards its reads the same way. `validate` runs on every read, and again on every change while a client watches. A summary that has no owner yet reads as empty, so a new customer can watch for their account to appear. |
| 274 | |
| 275 | ## Act as a customer in stories |
| 276 | |
| 277 | ```diff lang="typescript" |
| 278 | // test/Account.test.ts |
| 279 | import { Account } from "../src/Account.aggregate.ts"; |
| 280 | import { Bank, BankHandlers } from "../src/Bank.model.ts"; |
| 281 | +import { CurrentActor } from "../src/CurrentActor.context.ts"; |
| 282 | +import { CustomerId } from "../src/Customer.id.ts"; |
| 283 | import { DepositMoney, MoneyDeposited } from "../src/DepositMoney.command.ts"; |
| 284 | import { NotOpen } from "../src/NotOpen.rejection.ts"; |
| 285 | // ... |
| 286 | |
| 287 | const story = Story.make(Bank, { layer: BankHandlers }); |
| 288 | +const asSam = Story.provide(CurrentActor, { customerId: CustomerId.make("sam") }); |
| 289 | const account = Account.ref("a-1"); |
| 290 | |
| 291 | it.effect("opens an account", () => |
| 292 | story( |
| 293 | + asSam, |
| 294 | Story.when(account, new OpenAccount({ owner: "sam" })), |
| 295 | Story.then(account, new AccountOpened({ owner: "sam" })), |
| 296 | // ... |
| 297 | it.effect("refuses to open an account twice", () => |
| 298 | story( |
| 299 | + asSam, |
| 300 | Story.given(account, new AccountOpened({ owner: "sam" })), |
| 301 | Story.when(account, new OpenAccount({ owner: "sam" })), |
| 302 | // ... |
| 303 | it.effect("deposits into an open account and replies with the balance", () => |
| 304 | story( |
| 305 | + asSam, |
| 306 | Story.given(account, new AccountOpened({ owner: "sam" })), |
| 307 | Story.when(account, new DepositMoney({ amount: 100 })), |
| 308 | // ... |
| 309 | |
| 310 | it.effect("refuses a deposit into an account that isn't open", () => |
| 311 | - story(Story.when(account, new DepositMoney({ amount: 100 })), Story.rejected(new NotOpen())), |
| 312 | + story( |
| 313 | + asSam, |
| 314 | + Story.when(account, new DepositMoney({ amount: 100 })), |
| 315 | + Story.rejected(new NotOpen()), |
| 316 | + ), |
| 317 | ); |
| 318 | |
| 319 | it.effect("refuses to withdraw more than the balance", () => |
| 320 | story( |
| 321 | + asSam, |
| 322 | Story.given( |
| 323 | account, |
| 324 | ``` |
| 325 | |
| 326 | ```diff lang="typescript" |
| 327 | // test/views.test.ts |
| 328 | import { AccountSummary } from "../src/AccountSummary.view.ts"; |
| 329 | import { Bank, BankHandlers } from "../src/Bank.model.ts"; |
| 330 | +import { CurrentActor } from "../src/CurrentActor.context.ts"; |
| 331 | +import { CustomerId } from "../src/Customer.id.ts"; |
| 332 | import { DepositMoney, MoneyDeposited } from "../src/DepositMoney.command.ts"; |
| 333 | import { AccountOpened } from "../src/OpenAccount.command.ts"; |
| 334 | // ... |
| 335 | |
| 336 | const story = Story.make(Bank, { layer: BankHandlers }); |
| 337 | +const asSam = Story.provide(CurrentActor, { customerId: CustomerId.make("sam") }); |
| 338 | const account = Account.ref("a-1"); |
| 339 | |
| 340 | it.effect("the summary follows the balance", () => |
| 341 | story( |
| 342 | + asSam, |
| 343 | Story.given(account, new AccountOpened({ owner: "sam" })), |
| 344 | Story.when(account, new DepositMoney({ amount: 100 })), |
| 345 | // ... |
| 346 | it.effect("the statement has one line per movement", () => |
| 347 | story( |
| 348 | + asSam, |
| 349 | Story.given(account, new AccountOpened({ owner: "sam" })), |
| 350 | Story.when(account, new DepositMoney({ amount: 100 })), |
| 351 | ``` |
| 352 | |
| 353 | ```diff lang="typescript" |
| 354 | // test/registration.test.ts |
| 355 | import { AccountSummary } from "../src/AccountSummary.view.ts"; |
| 356 | import { Bank, BankHandlers } from "../src/Bank.model.ts"; |
| 357 | +import { CurrentActor } from "../src/CurrentActor.context.ts"; |
| 358 | import { Customer } from "../src/Customer.aggregate.ts"; |
| 359 | +import { CustomerId } from "../src/Customer.id.ts"; |
| 360 | import { AccountOpened } from "../src/OpenAccount.command.ts"; |
| 361 | -import { CustomerRegistered, RegisterCustomer } from "../src/RegisterCustomer.command.ts"; |
| 362 | +import { CustomerRegistered, NotYou, RegisterCustomer } from "../src/RegisterCustomer.command.ts"; |
| 363 | |
| 364 | const story = Story.make(Bank, { layer: BankHandlers }); |
| 365 | const sam = Customer.ref("c-1"); |
| 366 | const samsAccount = Account.ref("c-1-main"); |
| 367 | +const as = (customerId: string) => |
| 368 | + Story.provide(CurrentActor, { customerId: CustomerId.make(customerId) }); |
| 369 | |
| 370 | it.effect("registering opens a main account", () => |
| 371 | story( |
| 372 | + as("c-1"), |
| 373 | Story.when(sam, new RegisterCustomer({ name: "sam" })), |
| 374 | Story.then(sam, new CustomerRegistered({ name: "sam" })), |
| 375 | // ... |
| 376 | ), |
| 377 | ); |
| 378 | + |
| 379 | +it.effect("a customer can only register themselves", () => |
| 380 | + story(as("c-2"), Story.when(sam, new RegisterCustomer({ name: "sam" })), Story.rejected(new NotYou())), |
| 381 | +); |
| 382 | ``` |
| 383 | |
| 384 | A story has no middleware, so `Story.provide` stands in for it, giving the following commands their `CurrentActor`. |
| 385 | |
| 386 | ## Expose an Api |
| 387 | |
| 388 | ```typescript |
| 389 | // src/BankApi.api.ts |
| 390 | import * as Domain from "@alchemy.run/domain"; |
| 391 | import { Bank } from "./Bank.model.ts"; |
| 392 | |
| 393 | export class BankApi extends Domain.Api("BankApi", { |
| 394 | model: Bank, |
| 395 | commands: ["RegisterCustomer", "DepositMoney", "WithdrawMoney"], |
| 396 | views: ["AccountSummary"], |
| 397 | }) {} |
| 398 | ``` |
| 399 | |
| 400 | An Api names its model and lists the commands and views a client may reach. Nothing in it needs a handler: the account decides the commands, and the model hosts the view. |
| 401 | |
| 402 | ## Test the Api |
| 403 | |
| 404 | ```typescript |
| 405 | // test/BankApi.test.ts |
| 406 | import { expect, it } from "@effect/vitest"; |
| 407 | import * as Domain from "@alchemy.run/domain"; |
| 408 | import * as Effect from "effect/Effect"; |
| 409 | import * as Layer from "effect/Layer"; |
| 410 | import type * as Scope from "effect/Scope"; |
| 411 | import * as Stream from "effect/Stream"; |
| 412 | import { AccountId } from "../src/Account.id.ts"; |
| 413 | import { Bank, BankHandlers } from "../src/Bank.model.ts"; |
| 414 | import { BankApi } from "../src/BankApi.api.ts"; |
| 415 | import { CustomerId } from "../src/Customer.id.ts"; |
| 416 | import { SessionLive, sessionClient } from "../src/Session.middleware.ts"; |
| 417 | |
| 418 | // The bank in memory, with the same middleware a Worker would serve. |
| 419 | const World = SessionLive.pipe( |
| 420 | Layer.provideMerge(Bank.layer(BankHandlers).pipe(Layer.provide(Domain.InMemory))), |
| 421 | ); |
| 422 | |
| 423 | const signedInAs = (customerId: string) => |
| 424 | BankApi.clientInProcess.pipe(Effect.provide(sessionClient(customerId))); |
| 425 | |
| 426 | const inBank = <A, E>(effect: Effect.Effect<A, E, Scope.Scope | Layer.Success<typeof World>>) => |
| 427 | effect.pipe(Effect.scoped, Effect.provide(World)); |
| 428 | |
| 429 | it.live("a customer registers, deposits, and reads only their own balance", () => |
| 430 | inBank( |
| 431 | Effect.gen(function* () { |
| 432 | const sam = yield* signedInAs("c-1"); |
| 433 | yield* sam.RegisterCustomer(CustomerId.make("c-1"), { name: "sam" }); |
| 434 | |
| 435 | // The policy opens the account shortly after; wait for its summary. |
| 436 | const accountId = AccountId.make("c-1-main"); |
| 437 | yield* sam.AccountSummary.watch(accountId).pipe( |
| 438 | Stream.map(({ state }) => state), |
| 439 | Stream.filter((summary) => summary?.owner === "c-1"), |
| 440 | Stream.runHead, |
| 441 | ); |
| 442 | |
| 443 | const { reply } = yield* sam.DepositMoney(accountId, { amount: 100 }); |
| 444 | expect(reply.balance).toBe(100); |
| 445 | |
| 446 | const alex = yield* signedInAs("c-2"); |
| 447 | const refused = yield* alex.AccountSummary.get(accountId).pipe(Effect.flip); |
| 448 | expect(refused._tag).toBe("NotOwner"); |
| 449 | }), |
| 450 | ), |
| 451 | ); |
| 452 | ``` |
| 453 | |
| 454 | `clientInProcess` calls the Api in the same process, through the real middleware. Each client is signed in as one customer, and someone else's balance comes back as `NotOwner`. |
| 455 | |
| 456 | ```sh |
| 457 | bun vitest run |
| 458 | ``` |
| 459 | |
| 460 | Every request now has a customer, every command and read checks it, and clients reach the bank through one typed Api. |
| 461 | |
| 462 | :::note |
| 463 | Next, [deploy the bank to Cloudflare](/domain/tutorial/part-5). For browser sessions and second factors, see [Sessions and middleware](/domain/sessions). |
| 464 | ::: |