@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

main
mdx 138 lines 7.76 KB
Raw
1 ---
2 title: Plain HTTP and OpenAPI
3 description: Publish an Api as a plain HTTP JSON API, with an OpenAPI document, from the same Api.
4 ---
5
6 An Api's typed client speaks Effect RPC. A partner, a script or a public API client often wants plain HTTP and JSON instead, with an OpenAPI document to generate its client from. `toHttpApi` from `@alchemy.run/domain/Http` gives you both from the Api you already have: an Effect `HttpApi` group with one endpoint per call the Api serves, the Layer that serves it, and the OpenAPI document of it.
7
8 ## Publish an Api
9
10 ```typescript title="packages/server/src/BankHttp.ts"
11 import * as DomainHttp from "@alchemy.run/domain/Http";
12 import { CustomerApi } from "@bank/domain/CustomerApi.api";
13
14 export const BankHttp = DomainHttp.toHttpApi(CustomerApi);
15 ```
16
17 Every call the Api serves becomes an endpoint. The Api is already the list of what a client may reach, so to publish less over HTTP, give HTTP clients their own, smaller Api, as in [Give each kind of client its own Api](/domain/api#give-each-kind-of-client-its-own-api).
18
19 `BankHttp` has:
20
21 | Field | Value |
22 | ---------- | ---------------------------------------------------------------------------------- |
23 | `group` | The `HttpApiGroup`, one endpoint per published call, named after the Api. |
24 | `api` | An `HttpApi` with only that group. |
25 | `layer` | The handlers of the group in `api`. |
26 | `layerFor` | `layerFor(MyHttpApi)`: the handlers of the group in your own `HttpApi`. |
27
28 ## Serve it
29
30 Serve it like any Effect `HttpApi`. In a Worker, provide the hosted model and the middleware Layers, as for the Api itself:
31
32 ```typescript title="packages/server/src/BankWorker.ts"
33 import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
34 import * as Etag from "effect/http/Etag";
35 import * as HttpPlatform from "effect/http/HttpPlatform";
36 import * as HttpRouter from "effect/http/HttpRouter";
37 import { BankHttp } from "./BankHttp.ts";
38
39 export default class BankWorker extends Cloudflare.Worker<BankWorker>()(
40 "BankWorker",
41 { main: import.meta.url },
42 Effect.gen(function* () {
43 return {
44 fetch: HttpApiBuilder.layer(BankHttp.api, { openapiPath: "/openapi.json" }).pipe(
45 Layer.provide(BankHttp.layer),
46 Layer.provide([HttpPlatform.layer, Etag.layer]),
47 HttpRouter.toHttpEffect,
48 ),
49 };
50 }).pipe(Effect.provide(BankLive)),
51 ) {}
52 ```
53
54 `OpenApi.fromApi(BankHttp.api)` gives the same document as `/openapi.json`, to write to a file or check in a test.
55
56 To serve the group next to your own endpoints, or under a prefix, add `BankHttp.group` to your own `HttpApi`, and provide `BankHttp.layerFor` with that `HttpApi`:
57
58 ```typescript
59 const PublicApi = HttpApi.make("Public").add(BankHttp.group.prefix("/v1")).add(StatusGroup);
60 const handlers = Layer.mergeAll(BankHttp.layerFor(PublicApi), StatusLive);
61 ```
62
63 ## Paths and methods
64
65 Each published call becomes one endpoint, by one rule:
66
67 | Call | Endpoint | Input |
68 | ------------------------------ | --------------------------- | -------------------------------------------------------- |
69 | A command | `POST /<Command>` | A JSON body: `target`, an optional `commandId`, and the input |
70 | A view's or aggregate's `get`, a stream's `peek` | `GET /<Name>/{key}` | `?stream=&version=` (from a receipt) waits for that write |
71 | A view's `snapshot` | `GET /<Name>/{key}/snapshot` | `?stream=&version=` waits for that write |
72 | A view's or stream's `list` | `GET /<Name>/{key}/list` | `?order=&take=&after=` |
73 | `watch` | `GET /<Name>/{key}/watch` | None. Answers with Server-Sent Events |
74 | `events` | `GET /<Name>/{key}/events` | `?after=` a cursor. Answers with Server-Sent Events |
75
76 A command's body is the same JSON as its RPC payload, and every answer is the same JSON the typed client receives: a command answers with its receipt (`reply`, `stream`, `version`), and a read with the key's state (`null` for a key with nothing in it) or a page. The key of a read is in the path, because a read takes no body. `GET /AccountSummary/c-1-main?stream=…&version=3` reads your own write after a deposit. `stream` and `version` go together.
77
78 ```shellsession
79 $ curl -X POST https://bank.example.com/DepositMoney \
80 -H 'content-type: application/json' -H 'cookie: session=…' \
81 -d '{"target":"c-1-main","input":{"amount":500}}'
82 {"reply":{"balance":1500},"stream":"Account/c-1-main","version":3}
83 ```
84
85 ## Live reads
86
87 `watch` and `events` answer with Server-Sent Events. Each value the typed client would receive is one event, its JSON in `data`: `{ state, cursor }` for `watch`, then one per change, and for `events` each entry, a `CaughtUp` frame, then live entries. A browser reads them with `EventSource`:
88
89 ```typescript
90 const summary = new EventSource(`/AccountSummary/${accountId}/watch`);
91 summary.onmessage = (event) => render(JSON.parse(event.data).state);
92 ```
93
94 The response starts once the read has its first value, so a read the middleware or `validate` refuses answers with that failure's status, like any other call. Once the stream is open, a failure ends it with an `effect/http-api/stream/failure` event whose `data` is the typed failure, such as `validate` refusing a change while a client watches.
95
96 `events?after=<cursor>` resumes after a cursor from `watch`, `snapshot` or an earlier entry, so a client that reconnects misses nothing.
97
98 ## Errors
99
100 A typed failure answers with its JSON (its `_tag` and data), at the status its schema's `httpApiStatus` annotation gives it, as for any Effect HttpApi error. Declare it on the rejection:
101
102 ```typescript
103 export class NotOwner extends Domain.Rejection("NotOwner", {}, { httpApiStatus: 403 }) {}
104 ```
105
106 A middleware error takes it where you declare it: `error: Unauthenticated.pipe(HttpApiSchema.status(401))`. A failure without one answers with 422: a rejection is a refused request, not a server fault.
107
108 Each failure is in the OpenAPI document under its status, with its schema. Input that the call's schema refuses is a 400 before it reaches the model. A failure that the call does not declare is a defect, a 500, as on the Api itself.
109
110 ## The same checks as the Api
111
112 Every call goes through the Api's own handlers, in process, with the HTTP request's headers. So the middleware of what it calls (a session from a cookie or a token), its `validate` and its rejections run exactly as for the typed client. The input is decoded once, by the endpoint, so a transform such as a `DateTimeUtc` field arrives as a date and is not decoded again.
113
114 ## Limits
115
116 A read's `where` filter is not published, since a filter does not fit in a URL. An endpoint's input and answer are the call's own JSON. To shape a public API differently, write your own `HttpApi` group and call the Api's client from its handlers:
117
118 ```typescript
119 const Partner = HttpApi.make("Partner").add(
120 HttpApiGroup.make("accounts").add(
121 HttpApiEndpoint.get("balance", "/balance/:id", {
122 params: { id: AccountId },
123 success: Schema.Struct({ balance: Schema.Number }),
124 }),
125 ),
126 );
127
128 const PartnerLive = HttpApiBuilder.group(Partner, "accounts", (handlers) =>
129 handlers.handle("balance", ({ params, request }) =>
130 Effect.gen(function* () {
131 const bank = yield* CustomerApi.clientInProcess;
132 // the caller's headers, so the view's middleware sees who is asking
133 const summary = yield* bank.AccountSummary.get(params.id, { headers: request.headers });
134 return { balance: summary?.balance ?? 0 };
135 }).pipe(Effect.scoped, Effect.orDie),
136 ),
137 );
138 ```