@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 86 lines 2.15 KB
Raw
1 ---
2 title: "Part 2: Create Tenant Databases"
3 description: Let a Worker create a database for each tenant.
4 sidebar:
5 order: 2
6 ---
7
8 Open `src/Api.ts`. The Worker creates, lists, and deletes tenant databases while it runs.
9
10 ## Give the Worker the group
11
12 ```diff lang="typescript"
13 Effect.gen(function* () {
14 + const tenants = yield* Turso.ManageDatabases(Tenants);
15 return { fetch };
16 }).pipe(Effect.provide(Turso.ManageDatabasesHttp))
17 ```
18
19 The Worker gets a Turso API token that only works on the `Tenants` group. It can create and delete databases there, and nowhere else.
20
21 ## Read the template's name
22
23 ```diff lang="typescript"
24 Effect.gen(function* () {
25 const tenants = yield* Turso.ManageDatabases(Tenants);
26 + const template = yield* Template;
27 + const templateName = yield* template.name;
28 return { fetch };
29 })
30 ```
31
32 `templateName` gives you the template's name inside a request.
33
34 ## Copy the template for a new tenant
35
36 ```diff lang="typescript"
37 case "POST": {
38 + const database = yield* tenants.create(tenant, {
39 + seed: { type: "database", name: yield* templateName },
40 + });
41 + return yield* HttpServerResponse.json({ tenant: database });
42 }
43 ```
44
45 `POST /tenants/acme` creates the `acme` database as a copy of the template. It has the `notes` table and no notes.
46
47 ## List tenants
48
49 ```diff lang="typescript"
50 if (tenant === undefined || tenant === "") {
51 + const databases = yield* tenants.list();
52 + const template = yield* templateName;
53 + return yield* HttpServerResponse.json({
54 + tenants: databases.map((d) => d.name).filter((name) => name !== template),
55 + });
56 }
57 ```
58
59 `list()` returns every database in the group. Leave out the template.
60
61 ## Delete a tenant
62
63 ```diff lang="typescript"
64 case "DELETE": {
65 + yield* tenants.delete(tenant);
66 + return yield* HttpServerResponse.json({ deleted: tenant });
67 }
68 ```
69
70 This deletes the tenant's database and all its notes.
71
72 ## Add the Worker to the Stack
73
74 ```diff lang="typescript"
75 // alchemy.run.ts
76 Effect.gen(function* () {
77 const template = yield* Template;
78 + const api = yield* Api;
79 return {
80 + url: api.url.as<string>(),
81 template: template.name,
82 };
83 }),
84 ```
85
86 In [Part 3](/turso/tutorial/part-3), you'll read and write each tenant's notes.