workspace.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { z } from "zod"
  2. import { fn } from "./util/fn"
  3. import { Actor } from "./actor"
  4. import { Database, eq } from "./drizzle"
  5. import { Identifier } from "./identifier"
  6. import { UserTable } from "./schema/user.sql"
  7. import { BillingTable } from "./schema/billing.sql"
  8. import { WorkspaceTable } from "./schema/workspace.sql"
  9. import { Key } from "./key"
  10. export namespace Workspace {
  11. export const create = fn(z.void(), async () => {
  12. const account = Actor.assert("account")
  13. const workspaceID = Identifier.create("workspace")
  14. await Database.transaction(async (tx) => {
  15. await tx.insert(WorkspaceTable).values({
  16. id: workspaceID,
  17. })
  18. await tx.insert(UserTable).values({
  19. workspaceID,
  20. id: Identifier.create("user"),
  21. email: account.properties.email,
  22. name: "",
  23. })
  24. await tx.insert(BillingTable).values({
  25. workspaceID,
  26. id: Identifier.create("billing"),
  27. balance: 0,
  28. })
  29. })
  30. await Actor.provide(
  31. "system",
  32. {
  33. workspaceID,
  34. },
  35. async () => {
  36. await Key.create({ name: "Default API Key" })
  37. },
  38. )
  39. return workspaceID
  40. })
  41. export async function list() {
  42. const account = Actor.assert("account")
  43. return Database.use(async (tx) => {
  44. return tx
  45. .select({
  46. id: WorkspaceTable.id,
  47. slug: WorkspaceTable.slug,
  48. name: WorkspaceTable.name,
  49. })
  50. .from(UserTable)
  51. .innerJoin(WorkspaceTable, eq(UserTable.workspaceID, WorkspaceTable.id))
  52. .where(eq(UserTable.email, account.properties.email))
  53. })
  54. }
  55. }