The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | --- |
| 2 | title: Api |
| 3 | description: How an Api publishes a model to one kind of client, how it's served, and how a typed client calls it. |
| 4 | --- |
| 5 | |
| 6 | import DAG from "../../../components/DAG.astro"; |
| 7 | |
| 8 | An Api is the interface a model publishes. It lists what one kind of client may reach: the commands it may send, and the views, streams and aggregates it may read. Everything else in the model stays private. |
| 9 | |
| 10 | An Api has no handlers of its own. Aggregates already decide commands and views already answer reads, so an Api only chooses which of them to expose. This chapter starts with what it means to publish a model, then covers what an Api can expose, declaring one, serving it, and calling it. |
| 11 | |
| 12 | ## Publish the model, keep the rest private |
| 13 | |
| 14 | A bounded context is meant to be used: by a web app, by a support console, by another context. DDD calls the interface it offers them a **published language**. It's the part of the model other people may depend on, and it's chosen on purpose. |
| 15 | |
| 16 | Publishing a slice of the model, rather than all of it, is what keeps the model free to change. Clients depend on `DepositMoney` and `AccountSummary`. They don't depend on how `Account` stores its state, which policies exist, or which projection feeds which table. You can rework all of those without breaking a client, as long as what you published still works. |
| 17 | |
| 18 | <DAG |
| 19 | nodes={[ |
| 20 | { id: "app", label: "Customer app", type: "a client", kind: "client", col: 0, row: 0 }, |
| 21 | { id: "api", label: "CustomerApi", type: "the published part", kind: "api", col: 1, row: 0 }, |
| 22 | { id: "deposit", label: "DepositMoney", type: "published", kind: "command", col: 2, row: 0 }, |
| 23 | { id: "summary", label: "AccountSummary", type: "published", kind: "view", col: 2, row: 1 }, |
| 24 | { id: "open", label: "OpenAccount", type: "internal", kind: "command", col: 2, row: 2 }, |
| 25 | { id: "policy", label: "a policy", type: "internal", kind: "policy", col: 1, row: 2 }, |
| 26 | ]} |
| 27 | edges={[ |
| 28 | { from: "app", to: "api" }, |
| 29 | { from: "api", to: "deposit" }, |
| 30 | { from: "api", to: "summary" }, |
| 31 | { from: "policy", to: "open" }, |
| 32 | ]} |
| 33 | caption="Clients reach what the Api lists. Everything else stays inside the model." |
| 34 | /> |
| 35 | |
| 36 | It's also the first line of the model's security. What isn't published can't be reached from outside at all. |
| 37 | |
| 38 | ## What an Api can expose |
| 39 | |
| 40 | An Api can expose four kinds of entry. Commands are what a client sends to change something. Views, streams and aggregates are what a client reads. |
| 41 | |
| 42 | Exposing an entry doesn't bypass its security. Each entry declares its own middleware and checks, and they run on every call that comes through the Api. |
| 43 | |
| 44 | <DAG |
| 45 | nodes={[ |
| 46 | { id: "client", label: "Client", type: "typed from the Api", kind: "client", col: 0, row: 1 }, |
| 47 | { id: "api", label: "CustomerApi", type: "Domain.Api", kind: "api", col: 1, row: 1 }, |
| 48 | { id: "command", label: "DepositMoney", type: "command · send", kind: "command", col: 2, row: 0 }, |
| 49 | { id: "view", label: "AccountSummary", type: "view · get, watch", kind: "view", col: 2, row: 1 }, |
| 50 | { id: "stream", label: "AccountCard", type: "stream · peek, watch", kind: "stream", col: 2, row: 2 }, |
| 51 | { id: "aggregate", label: "Account", type: "aggregate · get, events", kind: "aggregate", col: 2, row: 3 }, |
| 52 | ]} |
| 53 | edges={[ |
| 54 | { from: "client", to: "api" }, |
| 55 | { from: "api", to: "command" }, |
| 56 | { from: "api", to: "view" }, |
| 57 | { from: "api", to: "stream" }, |
| 58 | { from: "api", to: "aggregate" }, |
| 59 | ]} |
| 60 | caption="One Api, four kinds of entry. Each is guarded by its own middleware and rules." |
| 61 | /> |
| 62 | |
| 63 | Policies, projections and external systems are never on an Api. They run inside the model, and a client reaches what they produce through the entries above: a projection's [stream](/domain/stream), a view a policy feeds, or a store you serve yourself. |
| 64 | |
| 65 | ### Commands |
| 66 | |
| 67 | A command becomes a method that takes its target and input together, and returns the receipt with the reply. Its middleware runs first, and its aggregate's `decide` has the final say. |
| 68 | |
| 69 | ```typescript title="packages/server/test/apiEntries.ts" |
| 70 | const { reply } = yield* bank.DepositMoney(accountId, { amount: 500 }); |
| 71 | ``` |
| 72 | |
| 73 | ### Views |
| 74 | |
| 75 | A view becomes a namespace with five reads: `get` for the current state, `watch` for the state and every change, each with its cursor, `events` for its emitted events (history, a `CaughtUp` frame, then live), `list` for a page of them, and `snapshot` for the state with the cursor it is valid at. Streams and aggregates send the same shapes; see [Know when a live read is current](/domain/view#know-when-a-live-read-is-current). `get`, `list` and `snapshot` also take `atLeast`, to read your own write, and fail with `ConsistencyTimeout` if the view hasn't applied it within 10 seconds. Its middleware and `validate` decide who may read which key, on every read and on every change while a client watches. |
| 76 | |
| 77 | ```typescript title="packages/server/test/apiEntries.ts" |
| 78 | const summary = yield* bank.AccountSummary.get(accountId); |
| 79 | const summaries = bank.AccountSummary.watch(accountId); |
| 80 | const page = yield* bank.Statement.list(accountId, { order: "desc", take: 10 }); |
| 81 | ``` |
| 82 | |
| 83 | ### Streams |
| 84 | |
| 85 | A stream becomes a namespace like a view's, with `peek` in place of `get`: the latest entry is the current value. It's guarded the same way, by its middleware and `validate`, judged against the latest entry. See [Stream](/domain/stream). |
| 86 | |
| 87 | ```typescript title="packages/server/test/apiEntries.ts" |
| 88 | const card = yield* bank.AccountCard.peek(accountId); |
| 89 | const cards = bank.AccountCard.watch(accountId); |
| 90 | ``` |
| 91 | |
| 92 | ### Aggregates |
| 93 | |
| 94 | An aggregate can be read directly too: its current state with `get` and `watch`, and its committed events with `events`. It's only allowed on an Api if it declares a `read` contract, because its state is otherwise private to its rules. The contract names the middleware and the check every read must pass. |
| 95 | |
| 96 | ```typescript title="packages/domain/src/Account/Account.aggregate.ts" |
| 97 | read: { |
| 98 | middleware: [Session], |
| 99 | rejects: [NotOwner], |
| 100 | validate: Effect.fn(function* (_request, s) { |
| 101 | yield* mustOwn(s._tag === "Open" ? s.customerId : null); |
| 102 | }), |
| 103 | }, |
| 104 | ``` |
| 105 | |
| 106 | ```typescript title="packages/server/test/apiEntries.ts" |
| 107 | const account = yield* bank.Account.get(accountId); |
| 108 | const history = bank.Account.events(accountId, { after: 0 }); |
| 109 | ``` |
| 110 | |
| 111 | Reading an aggregate directly is handy for an account's own screen. For anything shaped for a question, like a statement or a dashboard, prefer a view: it keeps the aggregate's state free to change with its rules. |
| 112 | |
| 113 | ## List what a client may reach |
| 114 | |
| 115 | The tutorial's bank exposes registration, deposits, withdrawals and the account summary. |
| 116 | |
| 117 | ```typescript title="src/BankApi.api.ts" |
| 118 | export class BankApi extends Domain.Api("BankApi", { |
| 119 | model: Bank, |
| 120 | commands: ["RegisterCustomer", "DepositMoney", "WithdrawMoney"], |
| 121 | views: ["AccountSummary"], |
| 122 | }) {} |
| 123 | ``` |
| 124 | |
| 125 | `model` is the model the Api is over. `commands`, `views`, `streams` and `aggregates` name what of it a client may reach, and naming something the model doesn't hold is a type error. A kind you leave out is served whole, so `Domain.Api("BankApi", { model: Bank })` serves every command, view and stream, and every aggregate that declares `read`. `[]` serves none of a kind, and naming an aggregate without `read` is a type error. |
| 126 | |
| 127 | Leaving something out is how you keep it internal. `OpenAccount` isn't listed, because only the `MainAccountProvisioning` policy opens accounts. No client can send it, however it's built. |
| 128 | |
| 129 | ## Give each kind of client its own Api |
| 130 | |
| 131 | Different clients need different surfaces. In the example bank, customers and support agents use the same model through two Apis. |
| 132 | |
| 133 | ```typescript title="packages/domain/src/SupportApi.api.ts" |
| 134 | export class SupportApi extends Domain.Api("SupportApi", { |
| 135 | model: Bank, |
| 136 | commands: ["FreezeAccount", "ChangeOwner", "ApproveTransfer"], |
| 137 | views: ["AccountSummary", "AccountActivity"], |
| 138 | streams: [], |
| 139 | aggregates: [], |
| 140 | }) {} |
| 141 | ``` |
| 142 | |
| 143 | `FreezeAccount` and `ChangeOwner` are on the support Api and not the customer one. `AccountSummary` is on both. |
| 144 | |
| 145 | <DAG |
| 146 | nodes={[ |
| 147 | { id: "app", label: "Customer app", type: "web app", kind: "client" }, |
| 148 | { id: "console", label: "Support console", type: "internal tool", kind: "client" }, |
| 149 | { id: "customerApi", label: "CustomerApi", type: "for customers", kind: "api" }, |
| 150 | { id: "supportApi", label: "SupportApi", type: "for support", kind: "api" }, |
| 151 | { id: "bank", label: "Bank", type: "model" }, |
| 152 | ]} |
| 153 | edges={[ |
| 154 | { from: "app", to: "customerApi" }, |
| 155 | { from: "console", to: "supportApi" }, |
| 156 | { from: "customerApi", to: "bank" }, |
| 157 | { from: "supportApi", to: "bank" }, |
| 158 | ]} |
| 159 | caption="One model, published to two kinds of client." |
| 160 | /> |
| 161 | |
| 162 | Being on an Api doesn't mean anyone may use an entry for anything. Each entry still guards itself. A command's middleware establishes who's calling and its `decide` checks whether they may; a view's middleware and `validate` decide what they may see. So `AccountSummary` can sit on both Apis, and a customer still reads only their own accounts. |
| 163 | |
| 164 | ## Serve it |
| 165 | |
| 166 | An Api is served from a Worker. The Api class is an Effect: `yield* BankApi` gives you its `fetch`, and the Worker returns it as its own. This is the tutorial's bank: |
| 167 | |
| 168 | ```typescript title="src/BankWorker.ts" |
| 169 | const BankLive = SessionLive.pipe( |
| 170 | Layer.provideMerge(Bank.layer(BankHandlers)), |
| 171 | Layer.provide(DomainCloudflare.layerDurableObjects()), |
| 172 | ); |
| 173 | |
| 174 | export default class BankWorker extends Cloudflare.Worker<BankWorker>()( |
| 175 | "BankWorker", |
| 176 | { main: import.meta.url }, |
| 177 | Effect.gen(function* () { |
| 178 | const api = yield* BankApi; |
| 179 | return { fetch: api.fetch }; |
| 180 | }).pipe(Effect.provide(BankLive)), |
| 181 | ) {} |
| 182 | ``` |
| 183 | |
| 184 | `BankLive` is everything the handler needs: the model hosted on Durable Objects, with its policies and projections, and an implementation of every middleware the Api's entries declare, here the session check. Deploying the Worker deploys the Durable Objects with it. |
| 185 | |
| 186 | Commands, `get`, `peek` and `list` are plain requests. Live reads, `watch` and `events`, are upgraded to WebSockets connected to the Durable Object that owns the key, which pushes each change as it commits. |
| 187 | |
| 188 | A Worker can serve several Apis by routing on the path. The example bank serves customers on `/api` and support agents on `/support`: |
| 189 | |
| 190 | ```typescript title="packages/server/src/BankWorker.ts" |
| 191 | if (path.startsWith("/api")) return yield* customerApi.fetch; |
| 192 | if (path.startsWith("/support")) return yield* supportApi.fetch; |
| 193 | ``` |
| 194 | |
| 195 | See [Cloudflare Durable Objects](/domain/cloudflare) for how the model is hosted. |
| 196 | |
| 197 | ## Call it with a typed client |
| 198 | |
| 199 | `Api.client` builds a client typed from the Api's entries. Each command is a method that takes the target, the input, and optional call options like `headers`. Each view or aggregate is a namespace with its reads. |
| 200 | |
| 201 | ```typescript title="packages/domain/test/depositAndWatch.ts" |
| 202 | export const depositAndWatch = Effect.gen(function* () { |
| 203 | const bank = yield* CustomerApi.client; |
| 204 | const accountId = AccountId.make("c-1-main"); |
| 205 | const { reply } = yield* bank.DepositMoney(accountId, { amount: 1_000 }); |
| 206 | yield* Effect.log(`balance ${reply.balance}`); |
| 207 | yield* bank.AccountSummary.watch(accountId).pipe( |
| 208 | Stream.take(2), |
| 209 | Stream.runForEach(({ state }) => Effect.log(`balance is now ${state?.balance}`)), |
| 210 | ); |
| 211 | }); |
| 212 | ``` |
| 213 | |
| 214 | ## Choose a protocol |
| 215 | |
| 216 | The client needs to know how to reach the server. `Domain.protocolWebSocket(url)` sends commands and one-off reads over HTTP and opens a WebSocket for each live read; if the connection drops, the client reconnects and resumes from the last change it saw. `Domain.protocolHttp(url)` uses HTTP for everything, streaming live reads as long-running responses. |
| 217 | |
| 218 | Each protocol also has a shortcut on the Api that provides it: |
| 219 | |
| 220 | ```typescript |
| 221 | const bank = yield* CustomerApi.clientWebSocket(url); |
| 222 | // is short for |
| 223 | // CustomerApi.client.pipe(Effect.provide(Domain.protocolWebSocket(url))) |
| 224 | ``` |
| 225 | |
| 226 | ## Handle what can go wrong |
| 227 | |
| 228 | Every call's error type says exactly what can fail. It's one of the rejections the entry declares, like `InsufficientFunds`; an error from its middleware, like `Unauthorized`; or an `RpcClientError` when the server can't be reached. Because each is a tagged error, `Effect.catchTag` handles the cases you expect and leaves the rest to propagate. |
| 229 | |
| 230 | ```typescript title="packages/server/test/withdraw.ts" |
| 231 | export const withdraw = Effect.fn(function* (bank: CustomerClient, accountId: AccountId) { |
| 232 | const receipt = yield* bank.WithdrawMoney(accountId, { amount: 2_000 }, mfa).pipe( |
| 233 | Effect.catchTag("InsufficientFunds", (r) => Effect.fail(`only ${r.balance} available`)), |
| 234 | ); |
| 235 | return receipt.reply.balance; |
| 236 | }); |
| 237 | ``` |
| 238 | |
| 239 | ## Read an Api's commands and rejections |
| 240 | |
| 241 | `CustomerApi.commands` lists the Api's command classes, in order. `CustomerApi.rejections` is one Schema for every rejection they declare, so a UI message can hold a refusal as data: |
| 242 | |
| 243 | ```typescript |
| 244 | const Refused = Schema.TaggedStruct("Refused", { |
| 245 | commandId: Schema.String, |
| 246 | rejection: CustomerApi.rejections, // InsufficientFunds | NotOwner | ... |
| 247 | }); |
| 248 | ``` |
| 249 | |
| 250 | `Domain.Api.Any` is the type every Api fits. Use it for helpers you write once for all your Apis: |
| 251 | |
| 252 | ```typescript |
| 253 | const actionsOf = <A extends Domain.Api.Any>(api: A) => |
| 254 | api.commands.map((command) => ({ tag: command.tag, rejects: command.rejects })); |
| 255 | ``` |
| 256 | |
| 257 | ## Provide the client to an app |
| 258 | |
| 259 | An app usually wants one client for its whole lifetime. `CustomerApi.Client` is the client as a service, and `CustomerApi.layerClient` provides it. The app's entry point provides it once, with the protocol to use: |
| 260 | |
| 261 | ```typescript title="packages/web/src/entry.ts" |
| 262 | return CustomerApi.layerClient.pipe( |
| 263 | Layer.provide(Domain.protocolWebSocket(`${location.origin}/api`)), |
| 264 | Layer.provide(Socket.layerWebSocketConstructorGlobal), |
| 265 | ); |
| 266 | ``` |
| 267 | |
| 268 | Anything that sends a command asks for the client, and doesn't care how it's connected: |
| 269 | |
| 270 | ```typescript title="packages/web/src/Bank.ts" |
| 271 | const bank = yield* CustomerApi.Client; |
| 272 | ``` |
| 273 | |
| 274 | See [Integrate with foldkit](/domain/foldkit) for a full browser app. |
| 275 | |
| 276 | ## Call it in process |
| 277 | |
| 278 | Code in the same process as the model, like a webhook route, a scheduled job or a script, calls the Api with `clientInProcess`. It's the same typed client over `Domain.protocolInProcess`, which serves the Api right there: nothing goes over the network. Every entry's middleware still runs, from the middleware Layers in scope. |
| 279 | |
| 280 | Often that code has already checked who is calling, for example by verifying a webhook signature. Then it provides a middleware Layer that trusts that caller, to this client only. The Api the Worker serves keeps its real middleware. |
| 281 | |
| 282 | ```typescript title="src/PaymentsWebhook.ts" |
| 283 | const asSystem = Layer.succeed(Session, (effect) => |
| 284 | Effect.provideService(effect, CurrentActor, system("payments-webhook")), |
| 285 | ); |
| 286 | |
| 287 | export const depositFromWebhook = Effect.fn(function* (accountId: AccountId, amount: number) { |
| 288 | const bank = yield* CustomerApi.clientInProcess.pipe(Effect.provide(asSystem)); |
| 289 | return yield* bank.DepositMoney(accountId, { amount }); |
| 290 | }, Effect.scoped); |
| 291 | ``` |
| 292 | |
| 293 | The caller's `decide` and `validate` read the `CurrentActor` the trusted Layer provides, exactly as they read the one `SessionLive` provides. |
| 294 | |
| 295 | `clientInProcess` needs a `Scope`. In a Worker, build it per request, like the served Api: Workers forbid sharing I/O across requests. In a long-lived process, `CustomerApi.layerClientInProcess` provides `CustomerApi.Client` in process for the life of the Layer, so code that asks for the client runs the same in process or over the network. |
| 296 | |
| 297 | Tests use the same client. To test an Api end to end, including its middleware and every rejection, see [Testing an Api](/domain/testing-apis). |
| 298 | |
| 299 | To serve every call as a plain HTTP JSON API with an OpenAPI document, see [Plain HTTP and OpenAPI](/domain/http-api). |
| 300 | |
| 301 | To give an agent the Api's calls as tools, in the app or over MCP, see [MCP](/domain/mcp). |
| 302 | |
| 303 | To run the Api's calls from a terminal, see [CLI](/domain/cli). |
| 304 | |
| 305 | Next, [Story](/domain/story): how to state each rule as an example, and run it. |