@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 402 lines 11.5 KB
Raw
1 ---
2 title: Full-stack TanStack Start + RPC + Drizzle
3 description: Build a reactive full-stack app on AWS — a TanStack Start UI on CloudFront and Lambda that drives an Effect RPC Lambda over Drizzle and Aurora DSQL, with browser state wired through Effect 4's native atom RPC.
4 sidebar:
5 order: 15
6 ---
7
8 import PackageManagers from "../../../../components/PackageManagers.astro";
9
10 export const deps = `@distilled.cloud/aws @effect/atom-react @effect/sql-pg drizzle-orm effect`;
11 export const devDeps = `@alchemy.run/frontend-frameworks`;
12
13 [TanStack Start](/aws/frontend/tanstack-start) · [Effect RPC](/aws/apis/effect-rpc) · [Drizzle + DSQL](/aws/data/drizzle-dsql)
14
15 ## The shape
16
17 ```
18 Browser (React)
19 │ useAtomValue / useAtomSet (src/routes/index.tsx)
20 ▼
21 AtomRpc client (TodoRpcs) (src/rpc-client.ts)
22 │ HTTP POST /rpc (JSON)
23 ▼
24 TanStack Start Lambda — /rpc proxy (src/routes/rpc.ts)
25 │ fetch(process.env.BACKEND_URL)
26 ▼
27 Backend RPC Lambda (TodoRpcs) (src/backend/api.ts)
28 │ Drizzle.Postgres over DSQL.Connect
29 ▼
30 Aurora DSQL cluster
31 ```
32
33 The browser calls a same-origin `/rpc` route; the frontend Lambda forwards requests to the backend.
34
35 ## Install
36
37 <PackageManagers add={deps} dev={devDeps} />
38
39 ## 1. The shared RPC contract
40
41 Share the RPC contract between the backend and browser:
42
43 ```typescript
44 // src/backend/rpc.ts
45 import * as Schema from "effect/Schema";
46 import { Rpc, RpcGroup } from "effect/rpc";
47
48 export class Todo extends Schema.Class<Todo>("Todo")({
49 id: Schema.String,
50 text: Schema.String,
51 done: Schema.Boolean,
52 createdAt: Schema.Date,
53 }) {}
54
55 export class TodoNotFound extends Schema.TaggedError<TodoNotFound>()(
56 "TodoNotFound",
57 { message: Schema.String, id: Schema.String },
58 ) {}
59
60 export class TodoRpcs extends RpcGroup.make(
61 Rpc.make("listTodos", { success: Schema.Array(Todo) }),
62 Rpc.make("createTodo", { payload: { text: Schema.String }, success: Todo }),
63 Rpc.make("toggleTodo", {
64 payload: { id: Schema.String, done: Schema.Boolean },
65 success: Todo,
66 error: TodoNotFound,
67 }),
68 Rpc.make("deleteTodo", {
69 payload: { id: Schema.String },
70 success: Schema.String,
71 error: TodoNotFound,
72 }),
73 ) {}
74 ```
75
76 [RPC contracts and errors](/aws/apis/effect-rpc)
77
78 ## 2. The database
79
80 Copy `database.ts`, `bootstrap.ts`, and `client.ts` from the [DSQL example](https://github.com/alchemy-run/alchemy/tree/main/examples/aws-dsql-drizzle/src) into `src/backend/`. [Database setup](/aws/data/drizzle-dsql).
81
82 ## 3. The table
83
84 Copy the example's [`schema.ts`](https://github.com/alchemy-run/alchemy/blob/main/examples/aws-dsql-drizzle/src/schema.ts) into `src/backend/`. It targets `app.todos` with application-generated UUIDs, matching the bootstrap and role grants. Check [DSQL compatibility](/aws/data/drizzle-dsql#define-the-table) before extending it.
85
86 :::note
87 The Action in step 5 bootstraps the database without an HTTP `/setup` route; it is not a versioned migrator. To evolve the schema, generate migration files with the [DSQL migration workflow](/aws/data/drizzle-dsql#evolve-the-schema) (schema path `./src/backend/schema.ts`) and pass the directory to the cluster's `migrations` prop, which applies them on deploy.
88 :::
89
90 ## 4. The backend RPC Lambda
91
92 `connectDatabase` uses the non-admin `app_user` role with verified TLS. `DSQL.Connect` grants cluster-scoped `dsql:DbConnect` and signs IAM tokens locally; Drizzle opens the connection lazily and closes its pool with the invocation scope.
93
94 ```typescript
95 // src/backend/api.ts
96 import * as AWS from "@alchemy.run/aws";
97 import { eq } from "drizzle-orm";
98 import * as Effect from "effect/Effect";
99 import * as Layer from "effect/Layer";
100 import { RpcSerialization, RpcServer } from "effect/rpc";
101 import { connectDatabase } from "./client.ts";
102 import { Todo, TodoNotFound, TodoRpcs } from "./rpc.ts";
103 import { Todos } from "./schema.ts";
104
105 export default class Backend extends AWS.Lambda.Function<Backend>()(
106 "Backend",
107 {
108 main: import.meta.url,
109 functionUrl: true,
110 },
111 Effect.gen(function* () {
112 const db = yield* connectDatabase;
113
114 const handlers = TodoRpcs.toLayer({
115 listTodos: () =>
116 db
117 .select()
118 .from(Todos)
119 .orderBy(Todos.createdAt)
120 .pipe(
121 Effect.map((rows) => rows.map((row) => new Todo(row))),
122 Effect.orDie,
123 ),
124
125 createTodo: ({ text }) =>
126 db
127 .insert(Todos)
128 .values({
129 id: crypto.randomUUID(),
130 text,
131 done: false,
132 createdAt: new Date(),
133 })
134 .returning()
135 .pipe(
136 Effect.map(([row]) => new Todo(row)),
137 Effect.orDie,
138 ),
139
140 toggleTodo: ({ id, done }) =>
141 db
142 .update(Todos)
143 .set({ done })
144 .where(eq(Todos.id, id))
145 .returning()
146 .pipe(
147 Effect.orDie, // DB errors -> defects; TodoNotFound below stays a failure
148 Effect.flatMap(([row]) =>
149 row
150 ? Effect.succeed(new Todo(row))
151 : new TodoNotFound({ message: `Todo ${id} not found`, id }),
152 ),
153 ),
154
155 deleteTodo: ({ id }) =>
156 db
157 .delete(Todos)
158 .where(eq(Todos.id, id))
159 .returning()
160 .pipe(
161 Effect.orDie,
162 Effect.flatMap(([row]) =>
163 row
164 ? Effect.succeed(row.id)
165 : new TodoNotFound({ message: `Todo ${id} not found`, id }),
166 ),
167 ),
168 });
169
170 const rpc = yield* RpcServer.toHttpEffect(TodoRpcs).pipe(
171 Effect.provide(Layer.mergeAll(handlers, RpcSerialization.layerJson)),
172 );
173
174 return { fetch: rpc.pipe(Effect.orDie) };
175 }).pipe(Effect.provide(AWS.DSQL.ConnectHttp)),
176 ) {}
177 ```
178
179 `Effect.orDie` handles database failures before `flatMap`, preserving the typed `TodoNotFound` failure. Client and server must both use `RpcSerialization.layerJson`.
180
181 ## 5. Wire it into the Stack
182
183 ```typescript
184 // alchemy.run.ts
185 import * as Alchemy from "alchemy";
186 import * as AWS from "@alchemy.run/aws";
187 import * as Effect from "effect/Effect";
188 import Backend from "./src/backend/api.ts";
189 import { BootstrapDatabase } from "./src/backend/bootstrap.ts";
190 import { Database } from "./src/backend/database.ts";
191
192 export default Alchemy.Stack(
193 "AwsTanstackRpcDrizzle",
194 {
195 providers: AWS.providers(),
196 state: AWS.state(),
197 },
198 Effect.gen(function* () {
199 const backend = yield* Backend.pipe(Alchemy.remote());
200 const cluster = yield* Database;
201 const schemaVersion = yield* BootstrapDatabase({
202 endpoint: cluster.endpoint,
203 roleArn: backend.roleArn,
204 version: "1",
205 });
206
207 const site = yield* AWS.Website.TanStackStart("Website", {
208 env: { BACKEND_URL: backend.functionUrl },
209 });
210
211 return {
212 websiteUrl: site.url,
213 backendUrl: backend.functionUrl,
214 schemaVersion,
215 };
216 }),
217 );
218 ```
219
220 `BootstrapDatabase` initializes the schema. `Alchemy.remote()` keeps the backend on AWS during local development.
221
222 :::caution
223 The backend Function URL is public. Add authentication before exposing private data; `AWS_IAM` requires SigV4-signed proxy requests.
224 :::
225
226 ## 6. The `/rpc` proxy route
227
228 Forward POST requests to the backend:
229
230 ```typescript
231 // src/routes/rpc.ts
232 import { createFileRoute } from "@tanstack/react-router";
233
234 export const Route = createFileRoute("/rpc")({
235 server: {
236 handlers: {
237 POST: async ({ request }) =>
238 fetch(process.env.BACKEND_URL!, {
239 method: "POST",
240 headers: { "content-type": "application/json" },
241 body: await request.text(),
242 }),
243 },
244 },
245 });
246 ```
247
248 ## 7. The atom RPC client
249
250 Create the browser client with Effect 4’s `AtomRpc`:
251
252 ```typescript
253 // src/rpc-client.ts
254 import * as Layer from "effect/Layer";
255 import * as FetchHttpClient from "effect/http/FetchHttpClient";
256 import * as AtomRpc from "effect/reactivity/AtomRpc";
257 import { RpcClient, RpcSerialization } from "effect/rpc";
258 import { TodoRpcs } from "./backend/rpc.ts";
259
260 export class TodoClient extends AtomRpc.Service<TodoClient>()("TodoClient", {
261 group: TodoRpcs,
262 protocol: RpcClient.layerProtocolHttp({ url: "/rpc" }).pipe(
263 Layer.provide(FetchHttpClient.layer),
264 Layer.provide(RpcSerialization.layerJson),
265 ),
266 }) {}
267
268 // Created once at module scope so their identity is stable across renders.
269 export const listTodosAtom = TodoClient.query("listTodos", undefined, {
270 reactivityKeys: ["todos"],
271 });
272 export const createTodoAtom = TodoClient.mutation("createTodo");
273 export const toggleTodoAtom = TodoClient.mutation("toggleTodo");
274 export const deleteTodoAtom = TodoClient.mutation("deleteTodo");
275 ```
276
277 Mutations with `reactivityKeys: ["todos"]` invalidate and refetch the list.
278
279 ## 8. Provide a registry
280
281 Wrap the application in `RegistryProvider`:
282
283 ```tsx
284 // src/routes/__root.tsx
285 import { RegistryProvider } from "@effect/atom-react";
286 import { Outlet, createRootRoute } from "@tanstack/react-router";
287
288 export const Route = createRootRoute({ component: RootComponent });
289
290 function RootComponent() {
291 return (
292 // One AtomRegistry for the whole app — every query/mutation atom
293 // resolves against it.
294 <RegistryProvider>
295 <Outlet />
296 </RegistryProvider>
297 );
298 }
299 ```
300
301 ## 9. The UI
302
303 Read the query with `useAtomValue`; call mutations with `useAtomSet`:
304
305 ```tsx
306 // src/routes/index.tsx
307 import { useAtomSet, useAtomValue } from "@effect/atom-react";
308 import * as AsyncResult from "effect/reactivity/AsyncResult";
309 import { useState } from "react";
310 import {
311 createTodoAtom,
312 deleteTodoAtom,
313 listTodosAtom,
314 toggleTodoAtom,
315 } from "../rpc-client.ts";
316
317 function TodoForm() {
318 const createTodo = useAtomSet(createTodoAtom);
319 const [text, setText] = useState("");
320
321 return (
322 <form
323 onSubmit={(e) => {
324 e.preventDefault();
325 const value = text.trim();
326 if (!value) return;
327 createTodo({ payload: { text: value }, reactivityKeys: ["todos"] });
328 setText("");
329 }}
330 >
331 <input value={text} onChange={(e) => setText(e.target.value)} />
332 <button type="submit">Add</button>
333 </form>
334 );
335 }
336
337 function TodoList() {
338 const atom = useAtomValue(listTodosAtom);
339 const toggleTodo = useAtomSet(toggleTodoAtom);
340 const deleteTodo = useAtomSet(deleteTodoAtom);
341
342 const todos = AsyncResult.getOrElse(atom, () => []);
343
344 if (AsyncResult.isWaiting(atom) && !todos.length) {
345 return <p>Loading todos…</p>;
346 }
347
348 return (
349 <ul>
350 {todos.map((todo) => (
351 <li key={todo.id}>
352 <input
353 type="checkbox"
354 checked={todo.done}
355 onChange={() =>
356 toggleTodo({
357 payload: { id: todo.id, done: !todo.done },
358 reactivityKeys: ["todos"],
359 })
360 }
361 />
362 <span>{todo.text}</span>
363 <button
364 type="button"
365 onClick={() =>
366 deleteTodo({ payload: { id: todo.id }, reactivityKeys: ["todos"] })
367 }
368 >
369 Delete
370 </button>
371 </li>
372 ))}
373 </ul>
374 );
375 }
376 ```
377
378 ## 10. Deploy
379
380 [AWS setup](/aws/setup)
381
382 ```sh
383 bun alchemy deploy
384 ```
385
386 Open `websiteUrl` to create, toggle, and delete todos.
387
388 ## Local dev
389
390 ```sh
391 bun alchemy dev
392 ```
393
394 The frontend runs locally; the backend Lambda and DSQL remain on AWS and incur charges.
395
396 ## Recap
397
398 `TodoRpcs` defines the API; the frontend proxies `/rpc`; mutation keys refresh the list.
399
400 ## Where to go next
401
402 [Effect RPC](/aws/apis/effect-rpc) · [TanStack Start](/aws/frontend/tanstack-start) · [Drizzle + DSQL](/aws/data/drizzle-dsql) · [Drizzle queries](/sql/drizzle/postgres) · [RDS & Aurora](/aws/data/rds)